3 * https://www.mediawiki.org/wiki/OOUI
5 * Copyright 2011–2018 OOUI Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
9 * Date: 2018-11-01T02:03:33Z
16 * Namespace for all classes, static methods and static properties.
48 * Constants for MouseEvent.which
52 OO
.ui
.MouseButtons
= {
65 * Generate a unique ID for element
69 OO
.ui
.generateElementId = function () {
71 return 'ooui-' + OO
.ui
.elementId
;
75 * Check if an element is focusable.
76 * Inspired by :focusable in jQueryUI v1.11.4 - 2015-04-14
78 * @param {jQuery} $element Element to test
79 * @return {boolean} Element is focusable
81 OO
.ui
.isFocusableElement = function ( $element
) {
83 element
= $element
[ 0 ];
85 // Anything disabled is not focusable
86 if ( element
.disabled
) {
90 // Check if the element is visible
92 // This is quicker than calling $element.is( ':visible' )
93 $.expr
.pseudos
.visible( element
) &&
94 // Check that all parents are visible
95 !$element
.parents().addBack().filter( function () {
96 return $.css( this, 'visibility' ) === 'hidden';
102 // Check if the element is ContentEditable, which is the string 'true'
103 if ( element
.contentEditable
=== 'true' ) {
107 // Anything with a non-negative numeric tabIndex is focusable.
108 // Use .prop to avoid browser bugs
109 if ( $element
.prop( 'tabIndex' ) >= 0 ) {
113 // Some element types are naturally focusable
114 // (indexOf is much faster than regex in Chrome and about the
115 // same in FF: https://jsperf.com/regex-vs-indexof-array2)
116 nodeName
= element
.nodeName
.toLowerCase();
117 if ( [ 'input', 'select', 'textarea', 'button', 'object' ].indexOf( nodeName
) !== -1 ) {
121 // Links and areas are focusable if they have an href
122 if ( ( nodeName
=== 'a' || nodeName
=== 'area' ) && $element
.attr( 'href' ) !== undefined ) {
130 * Find a focusable child
132 * @param {jQuery} $container Container to search in
133 * @param {boolean} [backwards] Search backwards
134 * @return {jQuery} Focusable child, or an empty jQuery object if none found
136 OO
.ui
.findFocusable = function ( $container
, backwards
) {
137 var $focusable
= $( [] ),
138 // $focusableCandidates is a superset of things that
139 // could get matched by isFocusableElement
140 $focusableCandidates
= $container
141 .find( 'input, select, textarea, button, object, a, area, [contenteditable], [tabindex]' );
144 $focusableCandidates
= Array
.prototype.reverse
.call( $focusableCandidates
);
147 $focusableCandidates
.each( function () {
148 var $this = $( this );
149 if ( OO
.ui
.isFocusableElement( $this ) ) {
158 * Get the user's language and any fallback languages.
160 * These language codes are used to localize user interface elements in the user's language.
162 * In environments that provide a localization system, this function should be overridden to
163 * return the user's language(s). The default implementation returns English (en) only.
165 * @return {string[]} Language codes, in descending order of priority
167 OO
.ui
.getUserLanguages = function () {
172 * Get a value in an object keyed by language code.
174 * @param {Object.<string,Mixed>} obj Object keyed by language code
175 * @param {string|null} [lang] Language code, if omitted or null defaults to any user language
176 * @param {string} [fallback] Fallback code, used if no matching language can be found
177 * @return {Mixed} Local value
179 OO
.ui
.getLocalValue = function ( obj
, lang
, fallback
) {
182 // Requested language
186 // Known user language
187 langs
= OO
.ui
.getUserLanguages();
188 for ( i
= 0, len
= langs
.length
; i
< len
; i
++ ) {
195 if ( obj
[ fallback
] ) {
196 return obj
[ fallback
];
198 // First existing language
199 for ( lang
in obj
) {
207 * Check if a node is contained within another node
209 * Similar to jQuery#contains except a list of containers can be supplied
210 * and a boolean argument allows you to include the container in the match list
212 * @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in
213 * @param {HTMLElement} contained Node to find
214 * @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match, otherwise only match descendants
215 * @return {boolean} The node is in the list of target nodes
217 OO
.ui
.contains = function ( containers
, contained
, matchContainers
) {
219 if ( !Array
.isArray( containers
) ) {
220 containers
= [ containers
];
222 for ( i
= containers
.length
- 1; i
>= 0; i
-- ) {
223 if ( ( matchContainers
&& contained
=== containers
[ i
] ) || $.contains( containers
[ i
], contained
) ) {
231 * Return a function, that, as long as it continues to be invoked, will not
232 * be triggered. The function will be called after it stops being called for
233 * N milliseconds. If `immediate` is passed, trigger the function on the
234 * leading edge, instead of the trailing.
236 * Ported from: http://underscorejs.org/underscore.js
238 * @param {Function} func Function to debounce
239 * @param {number} [wait=0] Wait period in milliseconds
240 * @param {boolean} [immediate] Trigger on leading edge
241 * @return {Function} Debounced function
243 OO
.ui
.debounce = function ( func
, wait
, immediate
) {
248 later = function () {
251 func
.apply( context
, args
);
254 if ( immediate
&& !timeout
) {
255 func
.apply( context
, args
);
257 if ( !timeout
|| wait
) {
258 clearTimeout( timeout
);
259 timeout
= setTimeout( later
, wait
);
265 * Puts a console warning with provided message.
267 * @param {string} message Message
269 OO
.ui
.warnDeprecation = function ( message
) {
270 if ( OO
.getProp( window
, 'console', 'warn' ) !== undefined ) {
271 // eslint-disable-next-line no-console
272 console
.warn( message
);
277 * Returns a function, that, when invoked, will only be triggered at most once
278 * during a given window of time. If called again during that window, it will
279 * wait until the window ends and then trigger itself again.
281 * As it's not knowable to the caller whether the function will actually run
282 * when the wrapper is called, return values from the function are entirely
285 * @param {Function} func Function to throttle
286 * @param {number} wait Throttle window length, in milliseconds
287 * @return {Function} Throttled function
289 OO
.ui
.throttle = function ( func
, wait
) {
290 var context
, args
, timeout
,
294 previous
= OO
.ui
.now();
295 func
.apply( context
, args
);
298 // Check how long it's been since the last time the function was
299 // called, and whether it's more or less than the requested throttle
300 // period. If it's less, run the function immediately. If it's more,
301 // set a timeout for the remaining time -- but don't replace an
302 // existing timeout, since that'd indefinitely prolong the wait.
303 var remaining
= wait
- ( OO
.ui
.now() - previous
);
306 if ( remaining
<= 0 ) {
307 // Note: unless wait was ridiculously large, this means we'll
308 // automatically run the first time the function was called in a
309 // given period. (If you provide a wait period larger than the
310 // current Unix timestamp, you *deserve* unexpected behavior.)
311 clearTimeout( timeout
);
313 } else if ( !timeout
) {
314 timeout
= setTimeout( run
, remaining
);
320 * A (possibly faster) way to get the current timestamp as an integer
322 * @return {number} Current timestamp, in milliseconds since the Unix epoch
324 OO
.ui
.now
= Date
.now
|| function () {
325 return new Date().getTime();
329 * Reconstitute a JavaScript object corresponding to a widget created by
330 * the PHP implementation.
332 * This is an alias for `OO.ui.Element.static.infuse()`.
334 * @param {string|HTMLElement|jQuery} idOrNode
335 * A DOM id (if a string) or node for the widget to infuse.
336 * @param {Object} [config] Configuration options
337 * @return {OO.ui.Element}
338 * The `OO.ui.Element` corresponding to this (infusable) document node.
340 OO
.ui
.infuse = function ( idOrNode
, config
) {
341 return OO
.ui
.Element
.static.infuse( idOrNode
, config
);
346 * Message store for the default implementation of OO.ui.msg
348 * Environments that provide a localization system should not use this, but should override
349 * OO.ui.msg altogether.
354 // Tool tip for a button that moves items in a list down one place
355 'ooui-outline-control-move-down': 'Move item down',
356 // Tool tip for a button that moves items in a list up one place
357 'ooui-outline-control-move-up': 'Move item up',
358 // Tool tip for a button that removes items from a list
359 'ooui-outline-control-remove': 'Remove item',
360 // Label for the toolbar group that contains a list of all other available tools
361 'ooui-toolbar-more': 'More',
362 // Label for the fake tool that expands the full list of tools in a toolbar group
363 'ooui-toolgroup-expand': 'More',
364 // Label for the fake tool that collapses the full list of tools in a toolbar group
365 'ooui-toolgroup-collapse': 'Fewer',
366 // Default label for the tooltip for the button that removes a tag item
367 'ooui-item-remove': 'Remove',
368 // Default label for the accept button of a confirmation dialog
369 'ooui-dialog-message-accept': 'OK',
370 // Default label for the reject button of a confirmation dialog
371 'ooui-dialog-message-reject': 'Cancel',
372 // Title for process dialog error description
373 'ooui-dialog-process-error': 'Something went wrong',
374 // Label for process dialog dismiss error button, visible when describing errors
375 'ooui-dialog-process-dismiss': 'Dismiss',
376 // Label for process dialog retry action button, visible when describing only recoverable errors
377 'ooui-dialog-process-retry': 'Try again',
378 // Label for process dialog retry action button, visible when describing only warnings
379 'ooui-dialog-process-continue': 'Continue',
380 // Label for the file selection widget's select file button
381 'ooui-selectfile-button-select': 'Select a file',
382 // Label for the file selection widget if file selection is not supported
383 'ooui-selectfile-not-supported': 'File selection is not supported',
384 // Label for the file selection widget when no file is currently selected
385 'ooui-selectfile-placeholder': 'No file is selected',
386 // Label for the file selection widget's drop target
387 'ooui-selectfile-dragdrop-placeholder': 'Drop file here',
388 // Label for the help icon attached to a form field
389 'ooui-field-help': 'Help'
393 * Get a localized message.
395 * After the message key, message parameters may optionally be passed. In the default implementation,
396 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
397 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
398 * they support unnamed, ordered message parameters.
400 * In environments that provide a localization system, this function should be overridden to
401 * return the message translated in the user's language. The default implementation always returns
402 * English messages. An example of doing this with [jQuery.i18n](https://github.com/wikimedia/jquery.i18n)
406 * var i, iLen, button,
407 * messagePath = 'oojs-ui/dist/i18n/',
408 * languages = [ $.i18n().locale, 'ur', 'en' ],
411 * for ( i = 0, iLen = languages.length; i < iLen; i++ ) {
412 * languageMap[ languages[ i ] ] = messagePath + languages[ i ].toLowerCase() + '.json';
415 * $.i18n().load( languageMap ).done( function() {
416 * // Replace the built-in `msg` only once we've loaded the internationalization.
417 * // OOUI uses `OO.ui.deferMsg` for all initially-loaded messages. So long as
418 * // you put off creating any widgets until this promise is complete, no English
419 * // will be displayed.
420 * OO.ui.msg = $.i18n;
422 * // A button displaying "OK" in the default locale
423 * button = new OO.ui.ButtonWidget( {
424 * label: OO.ui.msg( 'ooui-dialog-message-accept' ),
427 * $( 'body' ).append( button.$element );
429 * // A button displaying "OK" in Urdu
430 * $.i18n().locale = 'ur';
431 * button = new OO.ui.ButtonWidget( {
432 * label: OO.ui.msg( 'ooui-dialog-message-accept' ),
435 * $( 'body' ).append( button.$element );
438 * @param {string} key Message key
439 * @param {...Mixed} [params] Message parameters
440 * @return {string} Translated message with parameters substituted
442 OO
.ui
.msg = function ( key
) {
443 var message
= messages
[ key
],
444 params
= Array
.prototype.slice
.call( arguments
, 1 );
445 if ( typeof message
=== 'string' ) {
446 // Perform $1 substitution
447 message
= message
.replace( /\$(\d+)/g, function ( unused
, n
) {
448 var i
= parseInt( n
, 10 );
449 return params
[ i
- 1 ] !== undefined ? params
[ i
- 1 ] : '$' + n
;
452 // Return placeholder if message not found
453 message
= '[' + key
+ ']';
460 * Package a message and arguments for deferred resolution.
462 * Use this when you are statically specifying a message and the message may not yet be present.
464 * @param {string} key Message key
465 * @param {...Mixed} [params] Message parameters
466 * @return {Function} Function that returns the resolved message when executed
468 OO
.ui
.deferMsg = function () {
469 var args
= arguments
;
471 return OO
.ui
.msg
.apply( OO
.ui
, args
);
478 * If the message is a function it will be executed, otherwise it will pass through directly.
480 * @param {Function|string} msg Deferred message, or message text
481 * @return {string} Resolved message
483 OO
.ui
.resolveMsg = function ( msg
) {
484 if ( $.isFunction( msg
) ) {
491 * @param {string} url
494 OO
.ui
.isSafeUrl = function ( url
) {
495 // Keep this function in sync with php/Tag.php
496 var i
, protocolWhitelist
;
498 function stringStartsWith( haystack
, needle
) {
499 return haystack
.substr( 0, needle
.length
) === needle
;
502 protocolWhitelist
= [
503 'bitcoin', 'ftp', 'ftps', 'geo', 'git', 'gopher', 'http', 'https', 'irc', 'ircs',
504 'magnet', 'mailto', 'mms', 'news', 'nntp', 'redis', 'sftp', 'sip', 'sips', 'sms', 'ssh',
505 'svn', 'tel', 'telnet', 'urn', 'worldwind', 'xmpp'
512 for ( i
= 0; i
< protocolWhitelist
.length
; i
++ ) {
513 if ( stringStartsWith( url
, protocolWhitelist
[ i
] + ':' ) ) {
518 // This matches '//' too
519 if ( stringStartsWith( url
, '/' ) || stringStartsWith( url
, './' ) ) {
522 if ( stringStartsWith( url
, '?' ) || stringStartsWith( url
, '#' ) ) {
530 * Check if the user has a 'mobile' device.
532 * For our purposes this means the user is primarily using an
533 * on-screen keyboard, touch input instead of a mouse and may
534 * have a physically small display.
536 * It is left up to implementors to decide how to compute this
537 * so the default implementation always returns false.
539 * @return {boolean} User is on a mobile device
541 OO
.ui
.isMobile = function () {
546 * Get the additional spacing that should be taken into account when displaying elements that are
547 * clipped to the viewport, e.g. dropdown menus and popups. This is meant to be overridden to avoid
548 * such menus overlapping any fixed headers/toolbars/navigation used by the site.
550 * @return {Object} Object with the properties 'top', 'right', 'bottom', 'left', each representing
551 * the extra spacing from that edge of viewport (in pixels)
553 OO
.ui
.getViewportSpacing = function () {
563 * Get the default overlay, which is used by various widgets when they are passed `$overlay: true`.
564 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
566 * @return {jQuery} Default overlay node
568 OO
.ui
.getDefaultOverlay = function () {
569 if ( !OO
.ui
.$defaultOverlay
) {
570 OO
.ui
.$defaultOverlay
= $( '<div>' ).addClass( 'oo-ui-defaultOverlay' );
571 $( 'body' ).append( OO
.ui
.$defaultOverlay
);
573 return OO
.ui
.$defaultOverlay
;
581 * Namespace for OOUI mixins.
583 * Mixins are named according to the type of object they are intended to
584 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
585 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
586 * is intended to be mixed in to an instance of OO.ui.Widget.
594 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
595 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
596 * connected to them and can't be interacted with.
602 * @param {Object} [config] Configuration options
603 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
604 * to the top level (e.g., the outermost div) of the element. See the [OOUI documentation on MediaWiki][2]
606 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches#cssExample
607 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
608 * @cfg {string} [text] Text to insert
609 * @cfg {Array} [content] An array of content elements to append (after #text).
610 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
611 * Instances of OO.ui.Element will have their $element appended.
612 * @cfg {jQuery} [$content] Content elements to append (after #text).
613 * @cfg {jQuery} [$element] Wrapper element. Defaults to a new element with #getTagName.
614 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
615 * Data can also be specified with the #setData method.
617 OO
.ui
.Element
= function OoUiElement( config
) {
618 if ( OO
.ui
.isDemo
) {
619 this.initialConfig
= config
;
621 // Configuration initialization
622 config
= config
|| {};
626 this.elementId
= null;
628 this.data
= config
.data
;
629 this.$element
= config
.$element
||
630 $( document
.createElement( this.getTagName() ) );
631 this.elementGroup
= null;
634 if ( Array
.isArray( config
.classes
) ) {
635 this.$element
.addClass( config
.classes
);
638 this.setElementId( config
.id
);
641 this.$element
.text( config
.text
);
643 if ( config
.content
) {
644 // The `content` property treats plain strings as text; use an
645 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
646 // appropriate $element appended.
647 this.$element
.append( config
.content
.map( function ( v
) {
648 if ( typeof v
=== 'string' ) {
649 // Escape string so it is properly represented in HTML.
650 return document
.createTextNode( v
);
651 } else if ( v
instanceof OO
.ui
.HtmlSnippet
) {
654 } else if ( v
instanceof OO
.ui
.Element
) {
660 if ( config
.$content
) {
661 // The `$content` property treats plain strings as HTML.
662 this.$element
.append( config
.$content
);
668 OO
.initClass( OO
.ui
.Element
);
670 /* Static Properties */
673 * The name of the HTML tag used by the element.
675 * The static value may be ignored if the #getTagName method is overridden.
681 OO
.ui
.Element
.static.tagName
= 'div';
686 * Reconstitute a JavaScript object corresponding to a widget created
687 * by the PHP implementation.
689 * @param {string|HTMLElement|jQuery} idOrNode
690 * A DOM id (if a string) or node for the widget to infuse.
691 * @param {Object} [config] Configuration options
692 * @return {OO.ui.Element}
693 * The `OO.ui.Element` corresponding to this (infusable) document node.
694 * For `Tag` objects emitted on the HTML side (used occasionally for content)
695 * the value returned is a newly-created Element wrapping around the existing
698 OO
.ui
.Element
.static.infuse = function ( idOrNode
, config
) {
699 var obj
= OO
.ui
.Element
.static.unsafeInfuse( idOrNode
, config
, false );
700 // Verify that the type matches up.
701 // FIXME: uncomment after T89721 is fixed, see T90929.
703 if ( !( obj instanceof this['class'] ) ) {
704 throw new Error( 'Infusion type mismatch!' );
711 * Implementation helper for `infuse`; skips the type check and has an
712 * extra property so that only the top-level invocation touches the DOM.
715 * @param {string|HTMLElement|jQuery} idOrNode
716 * @param {Object} [config] Configuration options
717 * @param {jQuery.Promise} [domPromise] A promise that will be resolved
718 * when the top-level widget of this infusion is inserted into DOM,
719 * replacing the original node; only used internally.
720 * @return {OO.ui.Element}
722 OO
.ui
.Element
.static.unsafeInfuse = function ( idOrNode
, config
, domPromise
) {
723 // look for a cached result of a previous infusion.
724 var id
, $elem
, error
, data
, cls
, parts
, parent
, obj
, top
, state
, infusedChildren
;
725 if ( typeof idOrNode
=== 'string' ) {
727 $elem
= $( document
.getElementById( id
) );
729 $elem
= $( idOrNode
);
730 id
= $elem
.attr( 'id' );
732 if ( !$elem
.length
) {
733 if ( typeof idOrNode
=== 'string' ) {
734 error
= 'Widget not found: ' + idOrNode
;
735 } else if ( idOrNode
&& idOrNode
.selector
) {
736 error
= 'Widget not found: ' + idOrNode
.selector
;
738 error
= 'Widget not found';
740 throw new Error( error
);
742 if ( $elem
[ 0 ].oouiInfused
) {
743 $elem
= $elem
[ 0 ].oouiInfused
;
745 data
= $elem
.data( 'ooui-infused' );
748 if ( data
=== true ) {
749 throw new Error( 'Circular dependency! ' + id
);
752 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
753 state
= data
.constructor.static.gatherPreInfuseState( $elem
, data
);
754 // restore dynamic state after the new element is re-inserted into DOM under infused parent
755 domPromise
.done( data
.restorePreInfuseState
.bind( data
, state
) );
756 infusedChildren
= $elem
.data( 'ooui-infused-children' );
757 if ( infusedChildren
&& infusedChildren
.length
) {
758 infusedChildren
.forEach( function ( data
) {
759 var state
= data
.constructor.static.gatherPreInfuseState( $elem
, data
);
760 domPromise
.done( data
.restorePreInfuseState
.bind( data
, state
) );
766 data
= $elem
.attr( 'data-ooui' );
768 throw new Error( 'No infusion data found: ' + id
);
771 data
= JSON
.parse( data
);
775 if ( !( data
&& data
._
) ) {
776 throw new Error( 'No valid infusion data found: ' + id
);
778 if ( data
._
=== 'Tag' ) {
779 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
780 return new OO
.ui
.Element( $.extend( {}, config
, { $element
: $elem
} ) );
782 parts
= data
._
.split( '.' );
783 cls
= OO
.getProp
.apply( OO
, [ window
].concat( parts
) );
784 if ( cls
=== undefined ) {
785 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
788 // Verify that we're creating an OO.ui.Element instance
791 while ( parent
!== undefined ) {
792 if ( parent
=== OO
.ui
.Element
) {
797 parent
= parent
.parent
;
800 if ( parent
!== OO
.ui
.Element
) {
801 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
806 domPromise
= top
.promise();
808 $elem
.data( 'ooui-infused', true ); // prevent loops
809 data
.id
= id
; // implicit
810 infusedChildren
= [];
811 data
= OO
.copy( data
, null, function deserialize( value
) {
813 if ( OO
.isPlainObject( value
) ) {
815 infused
= OO
.ui
.Element
.static.unsafeInfuse( value
.tag
, config
, domPromise
);
816 infusedChildren
.push( infused
);
817 // Flatten the structure
818 infusedChildren
.push
.apply( infusedChildren
, infused
.$element
.data( 'ooui-infused-children' ) || [] );
819 infused
.$element
.removeData( 'ooui-infused-children' );
822 if ( value
.html
!== undefined ) {
823 return new OO
.ui
.HtmlSnippet( value
.html
);
827 // allow widgets to reuse parts of the DOM
828 data
= cls
.static.reusePreInfuseDOM( $elem
[ 0 ], data
);
829 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
830 state
= cls
.static.gatherPreInfuseState( $elem
[ 0 ], data
);
832 // eslint-disable-next-line new-cap
833 obj
= new cls( $.extend( {}, config
, data
) );
834 // If anyone is holding a reference to the old DOM element,
835 // let's allow them to OO.ui.infuse() it and do what they expect, see T105828.
836 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
837 $elem
[ 0 ].oouiInfused
= obj
.$element
;
838 // now replace old DOM with this new DOM.
840 // An efficient constructor might be able to reuse the entire DOM tree of the original element,
841 // so only mutate the DOM if we need to.
842 if ( $elem
[ 0 ] !== obj
.$element
[ 0 ] ) {
843 $elem
.replaceWith( obj
.$element
);
847 obj
.$element
.data( 'ooui-infused', obj
);
848 obj
.$element
.data( 'ooui-infused-children', infusedChildren
);
849 // set the 'data-ooui' attribute so we can identify infused widgets
850 obj
.$element
.attr( 'data-ooui', '' );
851 // restore dynamic state after the new element is inserted into DOM
852 domPromise
.done( obj
.restorePreInfuseState
.bind( obj
, state
) );
857 * Pick out parts of `node`'s DOM to be reused when infusing a widget.
859 * This method **must not** make any changes to the DOM, only find interesting pieces and add them
860 * to `config` (which should then be returned). Actual DOM juggling should then be done by the
861 * constructor, which will be given the enhanced config.
864 * @param {HTMLElement} node
865 * @param {Object} config
868 OO
.ui
.Element
.static.reusePreInfuseDOM = function ( node
, config
) {
873 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of an HTML DOM node
874 * (and its children) that represent an Element of the same class and the given configuration,
875 * generated by the PHP implementation.
877 * This method is called just before `node` is detached from the DOM. The return value of this
878 * function will be passed to #restorePreInfuseState after the newly created widget's #$element
879 * is inserted into DOM to replace `node`.
882 * @param {HTMLElement} node
883 * @param {Object} config
886 OO
.ui
.Element
.static.gatherPreInfuseState = function () {
891 * Get a jQuery function within a specific document.
894 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
895 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
897 * @return {Function} Bound jQuery function
899 OO
.ui
.Element
.static.getJQuery = function ( context
, $iframe
) {
900 function wrapper( selector
) {
901 return $( selector
, wrapper
.context
);
904 wrapper
.context
= this.getDocument( context
);
907 wrapper
.$iframe
= $iframe
;
914 * Get the document of an element.
917 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
918 * @return {HTMLDocument|null} Document object
920 OO
.ui
.Element
.static.getDocument = function ( obj
) {
921 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
922 return ( obj
[ 0 ] && obj
[ 0 ].ownerDocument
) ||
923 // Empty jQuery selections might have a context
930 ( obj
.nodeType
=== Node
.DOCUMENT_NODE
&& obj
) ||
935 * Get the window of an element or document.
938 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
939 * @return {Window} Window object
941 OO
.ui
.Element
.static.getWindow = function ( obj
) {
942 var doc
= this.getDocument( obj
);
943 return doc
.defaultView
;
947 * Get the direction of an element or document.
950 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
951 * @return {string} Text direction, either 'ltr' or 'rtl'
953 OO
.ui
.Element
.static.getDir = function ( obj
) {
956 if ( obj
instanceof jQuery
) {
959 isDoc
= obj
.nodeType
=== Node
.DOCUMENT_NODE
;
960 isWin
= obj
.document
!== undefined;
961 if ( isDoc
|| isWin
) {
967 return $( obj
).css( 'direction' );
971 * Get the offset between two frames.
973 * TODO: Make this function not use recursion.
976 * @param {Window} from Window of the child frame
977 * @param {Window} [to=window] Window of the parent frame
978 * @param {Object} [offset] Offset to start with, used internally
979 * @return {Object} Offset object, containing left and top properties
981 OO
.ui
.Element
.static.getFrameOffset = function ( from, to
, offset
) {
982 var i
, len
, frames
, frame
, rect
;
988 offset
= { top
: 0, left
: 0 };
990 if ( from.parent
=== from ) {
994 // Get iframe element
995 frames
= from.parent
.document
.getElementsByTagName( 'iframe' );
996 for ( i
= 0, len
= frames
.length
; i
< len
; i
++ ) {
997 if ( frames
[ i
].contentWindow
=== from ) {
1003 // Recursively accumulate offset values
1005 rect
= frame
.getBoundingClientRect();
1006 offset
.left
+= rect
.left
;
1007 offset
.top
+= rect
.top
;
1008 if ( from !== to
) {
1009 this.getFrameOffset( from.parent
, offset
);
1016 * Get the offset between two elements.
1018 * The two elements may be in a different frame, but in that case the frame $element is in must
1019 * be contained in the frame $anchor is in.
1022 * @param {jQuery} $element Element whose position to get
1023 * @param {jQuery} $anchor Element to get $element's position relative to
1024 * @return {Object} Translated position coordinates, containing top and left properties
1026 OO
.ui
.Element
.static.getRelativePosition = function ( $element
, $anchor
) {
1027 var iframe
, iframePos
,
1028 pos
= $element
.offset(),
1029 anchorPos
= $anchor
.offset(),
1030 elementDocument
= this.getDocument( $element
),
1031 anchorDocument
= this.getDocument( $anchor
);
1033 // If $element isn't in the same document as $anchor, traverse up
1034 while ( elementDocument
!== anchorDocument
) {
1035 iframe
= elementDocument
.defaultView
.frameElement
;
1037 throw new Error( '$element frame is not contained in $anchor frame' );
1039 iframePos
= $( iframe
).offset();
1040 pos
.left
+= iframePos
.left
;
1041 pos
.top
+= iframePos
.top
;
1042 elementDocument
= iframe
.ownerDocument
;
1044 pos
.left
-= anchorPos
.left
;
1045 pos
.top
-= anchorPos
.top
;
1050 * Get element border sizes.
1053 * @param {HTMLElement} el Element to measure
1054 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1056 OO
.ui
.Element
.static.getBorders = function ( el
) {
1057 var doc
= el
.ownerDocument
,
1058 win
= doc
.defaultView
,
1059 style
= win
.getComputedStyle( el
, null ),
1061 top
= parseFloat( style
? style
.borderTopWidth
: $el
.css( 'borderTopWidth' ) ) || 0,
1062 left
= parseFloat( style
? style
.borderLeftWidth
: $el
.css( 'borderLeftWidth' ) ) || 0,
1063 bottom
= parseFloat( style
? style
.borderBottomWidth
: $el
.css( 'borderBottomWidth' ) ) || 0,
1064 right
= parseFloat( style
? style
.borderRightWidth
: $el
.css( 'borderRightWidth' ) ) || 0;
1075 * Get dimensions of an element or window.
1078 * @param {HTMLElement|Window} el Element to measure
1079 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1081 OO
.ui
.Element
.static.getDimensions = function ( el
) {
1083 doc
= el
.ownerDocument
|| el
.document
,
1084 win
= doc
.defaultView
;
1086 if ( win
=== el
|| el
=== doc
.documentElement
) {
1089 borders
: { top
: 0, left
: 0, bottom
: 0, right
: 0 },
1091 top
: $win
.scrollTop(),
1092 left
: $win
.scrollLeft()
1094 scrollbar
: { right
: 0, bottom
: 0 },
1098 bottom
: $win
.innerHeight(),
1099 right
: $win
.innerWidth()
1105 borders
: this.getBorders( el
),
1107 top
: $el
.scrollTop(),
1108 left
: $el
.scrollLeft()
1111 right
: $el
.innerWidth() - el
.clientWidth
,
1112 bottom
: $el
.innerHeight() - el
.clientHeight
1114 rect
: el
.getBoundingClientRect()
1120 * Get the number of pixels that an element's content is scrolled to the left.
1122 * Adapted from <https://github.com/othree/jquery.rtl-scroll-type>.
1123 * Original code copyright 2012 Wei-Ko Kao, licensed under the MIT License.
1125 * This function smooths out browser inconsistencies (nicely described in the README at
1126 * <https://github.com/othree/jquery.rtl-scroll-type>) and produces a result consistent
1127 * with Firefox's 'scrollLeft', which seems the sanest.
1131 * @param {HTMLElement|Window} el Element to measure
1132 * @return {number} Scroll position from the left.
1133 * If the element's direction is LTR, this is a positive number between `0` (initial scroll position)
1134 * and `el.scrollWidth - el.clientWidth` (furthest possible scroll position).
1135 * If the element's direction is RTL, this is a negative number between `0` (initial scroll position)
1136 * and `-el.scrollWidth + el.clientWidth` (furthest possible scroll position).
1138 OO
.ui
.Element
.static.getScrollLeft
= ( function () {
1139 var rtlScrollType
= null;
1142 var $definer
= $( '<div dir="rtl" style="font-size: 14px; width: 1px; height: 1px; position: absolute; top: -1000px; overflow: scroll">A</div>' ),
1143 definer
= $definer
[ 0 ];
1145 $definer
.appendTo( 'body' );
1146 if ( definer
.scrollLeft
> 0 ) {
1148 rtlScrollType
= 'default';
1150 definer
.scrollLeft
= 1;
1151 if ( definer
.scrollLeft
=== 0 ) {
1152 // Firefox, old Opera
1153 rtlScrollType
= 'negative';
1155 // Internet Explorer, Edge
1156 rtlScrollType
= 'reverse';
1162 return function getScrollLeft( el
) {
1163 var isRoot
= el
.window
=== el
||
1164 el
=== el
.ownerDocument
.body
||
1165 el
=== el
.ownerDocument
.documentElement
,
1166 scrollLeft
= isRoot
? $( window
).scrollLeft() : el
.scrollLeft
,
1167 // All browsers use the correct scroll type ('negative') on the root, so don't
1168 // do any fixups when looking at the root element
1169 direction
= isRoot
? 'ltr' : $( el
).css( 'direction' );
1171 if ( direction
=== 'rtl' ) {
1172 if ( rtlScrollType
=== null ) {
1175 if ( rtlScrollType
=== 'reverse' ) {
1176 scrollLeft
= -scrollLeft
;
1177 } else if ( rtlScrollType
=== 'default' ) {
1178 scrollLeft
= scrollLeft
- el
.scrollWidth
+ el
.clientWidth
;
1187 * Get the root scrollable element of given element's document.
1189 * On Blink-based browsers (Chrome etc.), `document.documentElement` can't be used to get or set
1190 * the scrollTop property; instead we have to use `document.body`. Changing and testing the value
1191 * lets us use 'body' or 'documentElement' based on what is working.
1193 * https://code.google.com/p/chromium/issues/detail?id=303131
1196 * @param {HTMLElement} el Element to find root scrollable parent for
1197 * @return {HTMLElement} Scrollable parent, `document.body` or `document.documentElement`
1198 * depending on browser
1200 OO
.ui
.Element
.static.getRootScrollableElement = function ( el
) {
1201 var scrollTop
, body
;
1203 if ( OO
.ui
.scrollableElement
=== undefined ) {
1204 body
= el
.ownerDocument
.body
;
1205 scrollTop
= body
.scrollTop
;
1208 // In some browsers (observed in Chrome 56 on Linux Mint 18.1),
1209 // body.scrollTop doesn't become exactly 1, but a fractional value like 0.76
1210 if ( Math
.round( body
.scrollTop
) === 1 ) {
1211 body
.scrollTop
= scrollTop
;
1212 OO
.ui
.scrollableElement
= 'body';
1214 OO
.ui
.scrollableElement
= 'documentElement';
1218 return el
.ownerDocument
[ OO
.ui
.scrollableElement
];
1222 * Get closest scrollable container.
1224 * Traverses up until either a scrollable element or the root is reached, in which case the root
1225 * scrollable element will be returned (see #getRootScrollableElement).
1228 * @param {HTMLElement} el Element to find scrollable container for
1229 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1230 * @return {HTMLElement} Closest scrollable container
1232 OO
.ui
.Element
.static.getClosestScrollableContainer = function ( el
, dimension
) {
1234 // Browsers do not correctly return the computed value of 'overflow' when 'overflow-x' and
1235 // 'overflow-y' have different values, so we need to check the separate properties.
1236 props
= [ 'overflow-x', 'overflow-y' ],
1237 $parent
= $( el
).parent();
1239 if ( dimension
=== 'x' || dimension
=== 'y' ) {
1240 props
= [ 'overflow-' + dimension
];
1243 // Special case for the document root (which doesn't really have any scrollable container, since
1244 // it is the ultimate scrollable container, but this is probably saner than null or exception)
1245 if ( $( el
).is( 'html, body' ) ) {
1246 return this.getRootScrollableElement( el
);
1249 while ( $parent
.length
) {
1250 if ( $parent
[ 0 ] === this.getRootScrollableElement( el
) ) {
1251 return $parent
[ 0 ];
1255 val
= $parent
.css( props
[ i
] );
1256 // We assume that elements with 'overflow' (in any direction) set to 'hidden' will never be
1257 // scrolled in that direction, but they can actually be scrolled programatically. The user can
1258 // unintentionally perform a scroll in such case even if the application doesn't scroll
1259 // programatically, e.g. when jumping to an anchor, or when using built-in find functionality.
1260 // This could cause funny issues...
1261 if ( val
=== 'auto' || val
=== 'scroll' ) {
1262 return $parent
[ 0 ];
1265 $parent
= $parent
.parent();
1267 // The element is unattached... return something mostly sane
1268 return this.getRootScrollableElement( el
);
1272 * Scroll element into view.
1275 * @param {HTMLElement} el Element to scroll into view
1276 * @param {Object} [config] Configuration options
1277 * @param {string} [config.duration='fast'] jQuery animation duration value
1278 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1279 * to scroll in both directions
1280 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1282 OO
.ui
.Element
.static.scrollIntoView = function ( el
, config
) {
1283 var position
, animations
, container
, $container
, elementDimensions
, containerDimensions
, $window
,
1284 deferred
= $.Deferred();
1286 // Configuration initialization
1287 config
= config
|| {};
1290 container
= this.getClosestScrollableContainer( el
, config
.direction
);
1291 $container
= $( container
);
1292 elementDimensions
= this.getDimensions( el
);
1293 containerDimensions
= this.getDimensions( container
);
1294 $window
= $( this.getWindow( el
) );
1296 // Compute the element's position relative to the container
1297 if ( $container
.is( 'html, body' ) ) {
1298 // If the scrollable container is the root, this is easy
1300 top
: elementDimensions
.rect
.top
,
1301 bottom
: $window
.innerHeight() - elementDimensions
.rect
.bottom
,
1302 left
: elementDimensions
.rect
.left
,
1303 right
: $window
.innerWidth() - elementDimensions
.rect
.right
1306 // Otherwise, we have to subtract el's coordinates from container's coordinates
1308 top
: elementDimensions
.rect
.top
- ( containerDimensions
.rect
.top
+ containerDimensions
.borders
.top
),
1309 bottom
: containerDimensions
.rect
.bottom
- containerDimensions
.borders
.bottom
- containerDimensions
.scrollbar
.bottom
- elementDimensions
.rect
.bottom
,
1310 left
: elementDimensions
.rect
.left
- ( containerDimensions
.rect
.left
+ containerDimensions
.borders
.left
),
1311 right
: containerDimensions
.rect
.right
- containerDimensions
.borders
.right
- containerDimensions
.scrollbar
.right
- elementDimensions
.rect
.right
1315 if ( !config
.direction
|| config
.direction
=== 'y' ) {
1316 if ( position
.top
< 0 ) {
1317 animations
.scrollTop
= containerDimensions
.scroll
.top
+ position
.top
;
1318 } else if ( position
.top
> 0 && position
.bottom
< 0 ) {
1319 animations
.scrollTop
= containerDimensions
.scroll
.top
+ Math
.min( position
.top
, -position
.bottom
);
1322 if ( !config
.direction
|| config
.direction
=== 'x' ) {
1323 if ( position
.left
< 0 ) {
1324 animations
.scrollLeft
= containerDimensions
.scroll
.left
+ position
.left
;
1325 } else if ( position
.left
> 0 && position
.right
< 0 ) {
1326 animations
.scrollLeft
= containerDimensions
.scroll
.left
+ Math
.min( position
.left
, -position
.right
);
1329 if ( !$.isEmptyObject( animations
) ) {
1330 $container
.stop( true ).animate( animations
, config
.duration
=== undefined ? 'fast' : config
.duration
);
1331 $container
.queue( function ( next
) {
1338 return deferred
.promise();
1342 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1343 * and reserve space for them, because it probably doesn't.
1345 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1346 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1347 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1348 * and then reattach (or show) them back.
1351 * @param {HTMLElement} el Element to reconsider the scrollbars on
1353 OO
.ui
.Element
.static.reconsiderScrollbars = function ( el
) {
1354 var i
, len
, scrollLeft
, scrollTop
, nodes
= [];
1355 // Save scroll position
1356 scrollLeft
= el
.scrollLeft
;
1357 scrollTop
= el
.scrollTop
;
1358 // Detach all children
1359 while ( el
.firstChild
) {
1360 nodes
.push( el
.firstChild
);
1361 el
.removeChild( el
.firstChild
);
1364 void el
.offsetHeight
;
1365 // Reattach all children
1366 for ( i
= 0, len
= nodes
.length
; i
< len
; i
++ ) {
1367 el
.appendChild( nodes
[ i
] );
1369 // Restore scroll position (no-op if scrollbars disappeared)
1370 el
.scrollLeft
= scrollLeft
;
1371 el
.scrollTop
= scrollTop
;
1377 * Toggle visibility of an element.
1379 * @param {boolean} [show] Make element visible, omit to toggle visibility
1383 OO
.ui
.Element
.prototype.toggle = function ( show
) {
1384 show
= show
=== undefined ? !this.visible
: !!show
;
1386 if ( show
!== this.isVisible() ) {
1387 this.visible
= show
;
1388 this.$element
.toggleClass( 'oo-ui-element-hidden', !this.visible
);
1389 this.emit( 'toggle', show
);
1396 * Check if element is visible.
1398 * @return {boolean} element is visible
1400 OO
.ui
.Element
.prototype.isVisible = function () {
1401 return this.visible
;
1407 * @return {Mixed} Element data
1409 OO
.ui
.Element
.prototype.getData = function () {
1416 * @param {Mixed} data Element data
1419 OO
.ui
.Element
.prototype.setData = function ( data
) {
1425 * Set the element has an 'id' attribute.
1427 * @param {string} id
1430 OO
.ui
.Element
.prototype.setElementId = function ( id
) {
1431 this.elementId
= id
;
1432 this.$element
.attr( 'id', id
);
1437 * Ensure that the element has an 'id' attribute, setting it to an unique value if it's missing,
1438 * and return its value.
1442 OO
.ui
.Element
.prototype.getElementId = function () {
1443 if ( this.elementId
=== null ) {
1444 this.setElementId( OO
.ui
.generateElementId() );
1446 return this.elementId
;
1450 * Check if element supports one or more methods.
1452 * @param {string|string[]} methods Method or list of methods to check
1453 * @return {boolean} All methods are supported
1455 OO
.ui
.Element
.prototype.supports = function ( methods
) {
1459 methods
= Array
.isArray( methods
) ? methods
: [ methods
];
1460 for ( i
= 0, len
= methods
.length
; i
< len
; i
++ ) {
1461 if ( $.isFunction( this[ methods
[ i
] ] ) ) {
1466 return methods
.length
=== support
;
1470 * Update the theme-provided classes.
1472 * @localdoc This is called in element mixins and widget classes any time state changes.
1473 * Updating is debounced, minimizing overhead of changing multiple attributes and
1474 * guaranteeing that theme updates do not occur within an element's constructor
1476 OO
.ui
.Element
.prototype.updateThemeClasses = function () {
1477 OO
.ui
.theme
.queueUpdateElementClasses( this );
1481 * Get the HTML tag name.
1483 * Override this method to base the result on instance information.
1485 * @return {string} HTML tag name
1487 OO
.ui
.Element
.prototype.getTagName = function () {
1488 return this.constructor.static.tagName
;
1492 * Check if the element is attached to the DOM
1494 * @return {boolean} The element is attached to the DOM
1496 OO
.ui
.Element
.prototype.isElementAttached = function () {
1497 return $.contains( this.getElementDocument(), this.$element
[ 0 ] );
1501 * Get the DOM document.
1503 * @return {HTMLDocument} Document object
1505 OO
.ui
.Element
.prototype.getElementDocument = function () {
1506 // Don't cache this in other ways either because subclasses could can change this.$element
1507 return OO
.ui
.Element
.static.getDocument( this.$element
);
1511 * Get the DOM window.
1513 * @return {Window} Window object
1515 OO
.ui
.Element
.prototype.getElementWindow = function () {
1516 return OO
.ui
.Element
.static.getWindow( this.$element
);
1520 * Get closest scrollable container.
1522 * @return {HTMLElement} Closest scrollable container
1524 OO
.ui
.Element
.prototype.getClosestScrollableElementContainer = function () {
1525 return OO
.ui
.Element
.static.getClosestScrollableContainer( this.$element
[ 0 ] );
1529 * Get group element is in.
1531 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1533 OO
.ui
.Element
.prototype.getElementGroup = function () {
1534 return this.elementGroup
;
1538 * Set group element is in.
1540 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1543 OO
.ui
.Element
.prototype.setElementGroup = function ( group
) {
1544 this.elementGroup
= group
;
1549 * Scroll element into view.
1551 * @param {Object} [config] Configuration options
1552 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1554 OO
.ui
.Element
.prototype.scrollElementIntoView = function ( config
) {
1556 !this.isElementAttached() ||
1557 !this.isVisible() ||
1558 ( this.getElementGroup() && !this.getElementGroup().isVisible() )
1560 return $.Deferred().resolve();
1562 return OO
.ui
.Element
.static.scrollIntoView( this.$element
[ 0 ], config
);
1566 * Restore the pre-infusion dynamic state for this widget.
1568 * This method is called after #$element has been inserted into DOM. The parameter is the return
1569 * value of #gatherPreInfuseState.
1572 * @param {Object} state
1574 OO
.ui
.Element
.prototype.restorePreInfuseState = function () {
1578 * Wraps an HTML snippet for use with configuration values which default
1579 * to strings. This bypasses the default html-escaping done to string
1585 * @param {string} [content] HTML content
1587 OO
.ui
.HtmlSnippet
= function OoUiHtmlSnippet( content
) {
1589 this.content
= content
;
1594 OO
.initClass( OO
.ui
.HtmlSnippet
);
1601 * @return {string} Unchanged HTML snippet.
1603 OO
.ui
.HtmlSnippet
.prototype.toString = function () {
1604 return this.content
;
1608 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1609 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1610 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1611 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1612 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1616 * @extends OO.ui.Element
1617 * @mixins OO.EventEmitter
1620 * @param {Object} [config] Configuration options
1622 OO
.ui
.Layout
= function OoUiLayout( config
) {
1623 // Configuration initialization
1624 config
= config
|| {};
1626 // Parent constructor
1627 OO
.ui
.Layout
.parent
.call( this, config
);
1629 // Mixin constructors
1630 OO
.EventEmitter
.call( this );
1633 this.$element
.addClass( 'oo-ui-layout' );
1638 OO
.inheritClass( OO
.ui
.Layout
, OO
.ui
.Element
);
1639 OO
.mixinClass( OO
.ui
.Layout
, OO
.EventEmitter
);
1644 * Reset scroll offsets
1648 OO
.ui
.Layout
.prototype.resetScroll = function () {
1649 this.$element
[ 0 ].scrollTop
= 0;
1650 // TODO: Reset scrollLeft in an RTL-aware manner, see OO.ui.Element.static.getScrollLeft.
1656 * Widgets are compositions of one or more OOUI elements that users can both view
1657 * and interact with. All widgets can be configured and modified via a standard API,
1658 * and their state can change dynamically according to a model.
1662 * @extends OO.ui.Element
1663 * @mixins OO.EventEmitter
1666 * @param {Object} [config] Configuration options
1667 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1668 * appearance reflects this state.
1670 OO
.ui
.Widget
= function OoUiWidget( config
) {
1671 // Initialize config
1672 config
= $.extend( { disabled
: false }, config
);
1674 // Parent constructor
1675 OO
.ui
.Widget
.parent
.call( this, config
);
1677 // Mixin constructors
1678 OO
.EventEmitter
.call( this );
1681 this.disabled
= null;
1682 this.wasDisabled
= null;
1685 this.$element
.addClass( 'oo-ui-widget' );
1686 this.setDisabled( !!config
.disabled
);
1691 OO
.inheritClass( OO
.ui
.Widget
, OO
.ui
.Element
);
1692 OO
.mixinClass( OO
.ui
.Widget
, OO
.EventEmitter
);
1699 * A 'disable' event is emitted when the disabled state of the widget changes
1700 * (i.e. on disable **and** enable).
1702 * @param {boolean} disabled Widget is disabled
1708 * A 'toggle' event is emitted when the visibility of the widget changes.
1710 * @param {boolean} visible Widget is visible
1716 * Check if the widget is disabled.
1718 * @return {boolean} Widget is disabled
1720 OO
.ui
.Widget
.prototype.isDisabled = function () {
1721 return this.disabled
;
1725 * Set the 'disabled' state of the widget.
1727 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1729 * @param {boolean} disabled Disable widget
1732 OO
.ui
.Widget
.prototype.setDisabled = function ( disabled
) {
1735 this.disabled
= !!disabled
;
1736 isDisabled
= this.isDisabled();
1737 if ( isDisabled
!== this.wasDisabled
) {
1738 this.$element
.toggleClass( 'oo-ui-widget-disabled', isDisabled
);
1739 this.$element
.toggleClass( 'oo-ui-widget-enabled', !isDisabled
);
1740 this.$element
.attr( 'aria-disabled', isDisabled
.toString() );
1741 this.emit( 'disable', isDisabled
);
1742 this.updateThemeClasses();
1744 this.wasDisabled
= isDisabled
;
1750 * Update the disabled state, in case of changes in parent widget.
1754 OO
.ui
.Widget
.prototype.updateDisabled = function () {
1755 this.setDisabled( this.disabled
);
1760 * Get an ID of a labelable node which is part of this widget, if any, to be used for `<label for>`
1763 * If this function returns null, the widget should have a meaningful #simulateLabelClick method
1766 * @return {string|null} The ID of the labelable element
1768 OO
.ui
.Widget
.prototype.getInputId = function () {
1773 * Simulate the behavior of clicking on a label (a HTML `<label>` element) bound to this input.
1774 * HTML only allows `<label>` to act on specific "labelable" elements; complex widgets might need to
1775 * override this method to provide intuitive, accessible behavior.
1777 * By default, this does nothing. OO.ui.mixin.TabIndexedElement overrides it for focusable widgets.
1778 * Individual widgets may override it too.
1780 * This method is called by OO.ui.LabelWidget and OO.ui.FieldLayout. It should not be called
1783 OO
.ui
.Widget
.prototype.simulateLabelClick = function () {
1794 OO
.ui
.Theme
= function OoUiTheme() {
1795 this.elementClassesQueue
= [];
1796 this.debouncedUpdateQueuedElementClasses
= OO
.ui
.debounce( this.updateQueuedElementClasses
);
1801 OO
.initClass( OO
.ui
.Theme
);
1806 * Get a list of classes to be applied to a widget.
1808 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
1809 * otherwise state transitions will not work properly.
1811 * @param {OO.ui.Element} element Element for which to get classes
1812 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
1814 OO
.ui
.Theme
.prototype.getElementClasses = function () {
1815 return { on
: [], off
: [] };
1819 * Update CSS classes provided by the theme.
1821 * For elements with theme logic hooks, this should be called any time there's a state change.
1823 * @param {OO.ui.Element} element Element for which to update classes
1825 OO
.ui
.Theme
.prototype.updateElementClasses = function ( element
) {
1826 var $elements
= $( [] ),
1827 classes
= this.getElementClasses( element
);
1829 if ( element
.$icon
) {
1830 $elements
= $elements
.add( element
.$icon
);
1832 if ( element
.$indicator
) {
1833 $elements
= $elements
.add( element
.$indicator
);
1837 .removeClass( classes
.off
)
1838 .addClass( classes
.on
);
1844 OO
.ui
.Theme
.prototype.updateQueuedElementClasses = function () {
1846 for ( i
= 0; i
< this.elementClassesQueue
.length
; i
++ ) {
1847 this.updateElementClasses( this.elementClassesQueue
[ i
] );
1850 this.elementClassesQueue
= [];
1854 * Queue #updateElementClasses to be called for this element.
1856 * @localdoc QUnit tests override this method to directly call #queueUpdateElementClasses,
1857 * to make them synchronous.
1859 * @param {OO.ui.Element} element Element for which to update classes
1861 OO
.ui
.Theme
.prototype.queueUpdateElementClasses = function ( element
) {
1862 // Keep items in the queue unique. Use lastIndexOf to start checking from the end because that's
1863 // the most common case (this method is often called repeatedly for the same element).
1864 if ( this.elementClassesQueue
.lastIndexOf( element
) !== -1 ) {
1867 this.elementClassesQueue
.push( element
);
1868 this.debouncedUpdateQueuedElementClasses();
1872 * Get the transition duration in milliseconds for dialogs opening/closing
1874 * The dialog should be fully rendered this many milliseconds after the
1875 * ready process has executed.
1877 * @return {number} Transition duration in milliseconds
1879 OO
.ui
.Theme
.prototype.getDialogTransitionDuration = function () {
1884 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
1885 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
1886 * order in which users will navigate through the focusable elements via the "tab" key.
1889 * // TabIndexedElement is mixed into the ButtonWidget class
1890 * // to provide a tabIndex property.
1891 * var button1 = new OO.ui.ButtonWidget( {
1895 * var button2 = new OO.ui.ButtonWidget( {
1899 * var button3 = new OO.ui.ButtonWidget( {
1903 * var button4 = new OO.ui.ButtonWidget( {
1907 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
1913 * @param {Object} [config] Configuration options
1914 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
1915 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
1916 * functionality will be applied to it instead.
1917 * @cfg {string|number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
1918 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
1919 * to remove the element from the tab-navigation flow.
1921 OO
.ui
.mixin
.TabIndexedElement
= function OoUiMixinTabIndexedElement( config
) {
1922 // Configuration initialization
1923 config
= $.extend( { tabIndex
: 0 }, config
);
1926 this.$tabIndexed
= null;
1927 this.tabIndex
= null;
1930 this.connect( this, { disable
: 'onTabIndexedElementDisable' } );
1933 this.setTabIndex( config
.tabIndex
);
1934 this.setTabIndexedElement( config
.$tabIndexed
|| this.$element
);
1939 OO
.initClass( OO
.ui
.mixin
.TabIndexedElement
);
1944 * Set the element that should use the tabindex functionality.
1946 * This method is used to retarget a tabindex mixin so that its functionality applies
1947 * to the specified element. If an element is currently using the functionality, the mixin’s
1948 * effect on that element is removed before the new element is set up.
1950 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
1953 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndexedElement = function ( $tabIndexed
) {
1954 var tabIndex
= this.tabIndex
;
1955 // Remove attributes from old $tabIndexed
1956 this.setTabIndex( null );
1957 // Force update of new $tabIndexed
1958 this.$tabIndexed
= $tabIndexed
;
1959 this.tabIndex
= tabIndex
;
1960 return this.updateTabIndex();
1964 * Set the value of the tabindex.
1966 * @param {string|number|null} tabIndex Tabindex value, or `null` for no tabindex
1969 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndex = function ( tabIndex
) {
1970 tabIndex
= /^-?\d+$/.test( tabIndex
) ? Number( tabIndex
) : null;
1972 if ( this.tabIndex
!== tabIndex
) {
1973 this.tabIndex
= tabIndex
;
1974 this.updateTabIndex();
1981 * Update the `tabindex` attribute, in case of changes to tab index or
1987 OO
.ui
.mixin
.TabIndexedElement
.prototype.updateTabIndex = function () {
1988 if ( this.$tabIndexed
) {
1989 if ( this.tabIndex
!== null ) {
1990 // Do not index over disabled elements
1991 this.$tabIndexed
.attr( {
1992 tabindex
: this.isDisabled() ? -1 : this.tabIndex
,
1993 // Support: ChromeVox and NVDA
1994 // These do not seem to inherit aria-disabled from parent elements
1995 'aria-disabled': this.isDisabled().toString()
1998 this.$tabIndexed
.removeAttr( 'tabindex aria-disabled' );
2005 * Handle disable events.
2008 * @param {boolean} disabled Element is disabled
2010 OO
.ui
.mixin
.TabIndexedElement
.prototype.onTabIndexedElementDisable = function () {
2011 this.updateTabIndex();
2015 * Get the value of the tabindex.
2017 * @return {number|null} Tabindex value
2019 OO
.ui
.mixin
.TabIndexedElement
.prototype.getTabIndex = function () {
2020 return this.tabIndex
;
2024 * Get an ID of a focusable element of this widget, if any, to be used for `<label for>` value.
2026 * If the element already has an ID then that is returned, otherwise unique ID is
2027 * generated, set on the element, and returned.
2029 * @return {string|null} The ID of the focusable element
2031 OO
.ui
.mixin
.TabIndexedElement
.prototype.getInputId = function () {
2034 if ( !this.$tabIndexed
) {
2037 if ( !this.isLabelableNode( this.$tabIndexed
) ) {
2041 id
= this.$tabIndexed
.attr( 'id' );
2042 if ( id
=== undefined ) {
2043 id
= OO
.ui
.generateElementId();
2044 this.$tabIndexed
.attr( 'id', id
);
2051 * Whether the node is 'labelable' according to the HTML spec
2052 * (i.e., whether it can be interacted with through a `<label for="…">`).
2053 * See: <https://html.spec.whatwg.org/multipage/forms.html#category-label>.
2056 * @param {jQuery} $node
2059 OO
.ui
.mixin
.TabIndexedElement
.prototype.isLabelableNode = function ( $node
) {
2061 labelableTags
= [ 'button', 'meter', 'output', 'progress', 'select', 'textarea' ],
2062 tagName
= $node
.prop( 'tagName' ).toLowerCase();
2064 if ( tagName
=== 'input' && $node
.attr( 'type' ) !== 'hidden' ) {
2067 if ( labelableTags
.indexOf( tagName
) !== -1 ) {
2074 * Focus this element.
2078 OO
.ui
.mixin
.TabIndexedElement
.prototype.focus = function () {
2079 if ( !this.isDisabled() ) {
2080 this.$tabIndexed
.focus();
2086 * Blur this element.
2090 OO
.ui
.mixin
.TabIndexedElement
.prototype.blur = function () {
2091 this.$tabIndexed
.blur();
2096 * @inheritdoc OO.ui.Widget
2098 OO
.ui
.mixin
.TabIndexedElement
.prototype.simulateLabelClick = function () {
2103 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
2104 * interface element that can be configured with access keys for accessibility.
2105 * See the [OOUI documentation on MediaWiki] [1] for examples.
2107 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches#Buttons
2113 * @param {Object} [config] Configuration options
2114 * @cfg {jQuery} [$button] The button element created by the class.
2115 * If this configuration is omitted, the button element will use a generated `<a>`.
2116 * @cfg {boolean} [framed=true] Render the button with a frame
2118 OO
.ui
.mixin
.ButtonElement
= function OoUiMixinButtonElement( config
) {
2119 // Configuration initialization
2120 config
= config
|| {};
2123 this.$button
= null;
2125 this.active
= config
.active
!== undefined && config
.active
;
2126 this.onDocumentMouseUpHandler
= this.onDocumentMouseUp
.bind( this );
2127 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
2128 this.onDocumentKeyUpHandler
= this.onDocumentKeyUp
.bind( this );
2129 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
2130 this.onClickHandler
= this.onClick
.bind( this );
2131 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
2134 this.$element
.addClass( 'oo-ui-buttonElement' );
2135 this.toggleFramed( config
.framed
=== undefined || config
.framed
);
2136 this.setButtonElement( config
.$button
|| $( '<a>' ) );
2141 OO
.initClass( OO
.ui
.mixin
.ButtonElement
);
2143 /* Static Properties */
2146 * Cancel mouse down events.
2148 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
2149 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
2150 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
2155 * @property {boolean}
2157 OO
.ui
.mixin
.ButtonElement
.static.cancelButtonMouseDownEvents
= true;
2162 * A 'click' event is emitted when the button element is clicked.
2170 * Set the button element.
2172 * This method is used to retarget a button mixin so that its functionality applies to
2173 * the specified button element instead of the one created by the class. If a button element
2174 * is already set, the method will remove the mixin’s effect on that element.
2176 * @param {jQuery} $button Element to use as button
2178 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement = function ( $button
) {
2179 if ( this.$button
) {
2181 .removeClass( 'oo-ui-buttonElement-button' )
2182 .removeAttr( 'role accesskey' )
2184 mousedown
: this.onMouseDownHandler
,
2185 keydown
: this.onKeyDownHandler
,
2186 click
: this.onClickHandler
,
2187 keypress
: this.onKeyPressHandler
2191 this.$button
= $button
2192 .addClass( 'oo-ui-buttonElement-button' )
2194 mousedown
: this.onMouseDownHandler
,
2195 keydown
: this.onKeyDownHandler
,
2196 click
: this.onClickHandler
,
2197 keypress
: this.onKeyPressHandler
2200 // Add `role="button"` on `<a>` elements, where it's needed
2201 // `toUpperCase()` is added for XHTML documents
2202 if ( this.$button
.prop( 'tagName' ).toUpperCase() === 'A' ) {
2203 this.$button
.attr( 'role', 'button' );
2208 * Handles mouse down events.
2211 * @param {jQuery.Event} e Mouse down event
2213 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown = function ( e
) {
2214 if ( this.isDisabled() || e
.which
!== OO
.ui
.MouseButtons
.LEFT
) {
2217 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
2218 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
2219 // reliably remove the pressed class
2220 this.getElementDocument().addEventListener( 'mouseup', this.onDocumentMouseUpHandler
, true );
2221 // Prevent change of focus unless specifically configured otherwise
2222 if ( this.constructor.static.cancelButtonMouseDownEvents
) {
2228 * Handles document mouse up events.
2231 * @param {MouseEvent} e Mouse up event
2233 OO
.ui
.mixin
.ButtonElement
.prototype.onDocumentMouseUp = function ( e
) {
2234 if ( this.isDisabled() || e
.which
!== OO
.ui
.MouseButtons
.LEFT
) {
2237 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
2238 // Stop listening for mouseup, since we only needed this once
2239 this.getElementDocument().removeEventListener( 'mouseup', this.onDocumentMouseUpHandler
, true );
2242 // Deprecated alias since 0.28.3
2243 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp = function () {
2244 OO
.ui
.warnDeprecation( 'onMouseUp is deprecated, use onDocumentMouseUp instead' );
2245 this.onDocumentMouseUp
.apply( this, arguments
);
2249 * Handles mouse click events.
2252 * @param {jQuery.Event} e Mouse click event
2255 OO
.ui
.mixin
.ButtonElement
.prototype.onClick = function ( e
) {
2256 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
2257 if ( this.emit( 'click' ) ) {
2264 * Handles key down events.
2267 * @param {jQuery.Event} e Key down event
2269 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyDown = function ( e
) {
2270 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
2273 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
2274 // Run the keyup handler no matter where the key is when the button is let go, so we can
2275 // reliably remove the pressed class
2276 this.getElementDocument().addEventListener( 'keyup', this.onDocumentKeyUpHandler
, true );
2280 * Handles document key up events.
2283 * @param {KeyboardEvent} e Key up event
2285 OO
.ui
.mixin
.ButtonElement
.prototype.onDocumentKeyUp = function ( e
) {
2286 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
2289 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
2290 // Stop listening for keyup, since we only needed this once
2291 this.getElementDocument().removeEventListener( 'keyup', this.onDocumentKeyUpHandler
, true );
2294 // Deprecated alias since 0.28.3
2295 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyUp = function () {
2296 OO
.ui
.warnDeprecation( 'onKeyUp is deprecated, use onDocumentKeyUp instead' );
2297 this.onDocumentKeyUp
.apply( this, arguments
);
2301 * Handles key press events.
2304 * @param {jQuery.Event} e Key press event
2307 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyPress = function ( e
) {
2308 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
2309 if ( this.emit( 'click' ) ) {
2316 * Check if button has a frame.
2318 * @return {boolean} Button is framed
2320 OO
.ui
.mixin
.ButtonElement
.prototype.isFramed = function () {
2325 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
2327 * @param {boolean} [framed] Make button framed, omit to toggle
2330 OO
.ui
.mixin
.ButtonElement
.prototype.toggleFramed = function ( framed
) {
2331 framed
= framed
=== undefined ? !this.framed
: !!framed
;
2332 if ( framed
!== this.framed
) {
2333 this.framed
= framed
;
2335 .toggleClass( 'oo-ui-buttonElement-frameless', !framed
)
2336 .toggleClass( 'oo-ui-buttonElement-framed', framed
);
2337 this.updateThemeClasses();
2344 * Set the button's active state.
2346 * The active state can be set on:
2348 * - {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} when it is selected
2349 * - {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} when it is toggle on
2350 * - {@link OO.ui.ButtonWidget ButtonWidget} when clicking the button would only refresh the page
2353 * @param {boolean} value Make button active
2356 OO
.ui
.mixin
.ButtonElement
.prototype.setActive = function ( value
) {
2357 this.active
= !!value
;
2358 this.$element
.toggleClass( 'oo-ui-buttonElement-active', this.active
);
2359 this.updateThemeClasses();
2364 * Check if the button is active
2367 * @return {boolean} The button is active
2369 OO
.ui
.mixin
.ButtonElement
.prototype.isActive = function () {
2374 * Any OOUI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
2375 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
2376 * items from the group is done through the interface the class provides.
2377 * For more information, please see the [OOUI documentation on MediaWiki] [1].
2379 * [1]: https://www.mediawiki.org/wiki/OOUI/Elements/Groups
2382 * @mixins OO.EmitterList
2386 * @param {Object} [config] Configuration options
2387 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
2388 * is omitted, the group element will use a generated `<div>`.
2390 OO
.ui
.mixin
.GroupElement
= function OoUiMixinGroupElement( config
) {
2391 // Configuration initialization
2392 config
= config
|| {};
2394 // Mixin constructors
2395 OO
.EmitterList
.call( this, config
);
2401 this.setGroupElement( config
.$group
|| $( '<div>' ) );
2406 OO
.mixinClass( OO
.ui
.mixin
.GroupElement
, OO
.EmitterList
);
2413 * A change event is emitted when the set of selected items changes.
2415 * @param {OO.ui.Element[]} items Items currently in the group
2421 * Set the group element.
2423 * If an element is already set, items will be moved to the new element.
2425 * @param {jQuery} $group Element to use as group
2427 OO
.ui
.mixin
.GroupElement
.prototype.setGroupElement = function ( $group
) {
2430 this.$group
= $group
;
2431 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2432 this.$group
.append( this.items
[ i
].$element
);
2437 * Find an item by its data.
2439 * Only the first item with matching data will be returned. To return all matching items,
2440 * use the #findItemsFromData method.
2442 * @param {Object} data Item data to search for
2443 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
2445 OO
.ui
.mixin
.GroupElement
.prototype.findItemFromData = function ( data
) {
2447 hash
= OO
.getHash( data
);
2449 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2450 item
= this.items
[ i
];
2451 if ( hash
=== OO
.getHash( item
.getData() ) ) {
2460 * Find items by their data.
2462 * All items with matching data will be returned. To return only the first match, use the #findItemFromData method instead.
2464 * @param {Object} data Item data to search for
2465 * @return {OO.ui.Element[]} Items with equivalent data
2467 OO
.ui
.mixin
.GroupElement
.prototype.findItemsFromData = function ( data
) {
2469 hash
= OO
.getHash( data
),
2472 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2473 item
= this.items
[ i
];
2474 if ( hash
=== OO
.getHash( item
.getData() ) ) {
2483 * Add items to the group.
2485 * Items will be added to the end of the group array unless the optional `index` parameter specifies
2486 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
2488 * @param {OO.ui.Element[]} items An array of items to add to the group
2489 * @param {number} [index] Index of the insertion point
2492 OO
.ui
.mixin
.GroupElement
.prototype.addItems = function ( items
, index
) {
2494 OO
.EmitterList
.prototype.addItems
.call( this, items
, index
);
2496 this.emit( 'change', this.getItems() );
2503 OO
.ui
.mixin
.GroupElement
.prototype.moveItem = function ( items
, newIndex
) {
2504 // insertItemElements expects this.items to not have been modified yet, so call before the mixin
2505 this.insertItemElements( items
, newIndex
);
2508 newIndex
= OO
.EmitterList
.prototype.moveItem
.call( this, items
, newIndex
);
2516 OO
.ui
.mixin
.GroupElement
.prototype.insertItem = function ( item
, index
) {
2517 item
.setElementGroup( this );
2518 this.insertItemElements( item
, index
);
2521 index
= OO
.EmitterList
.prototype.insertItem
.call( this, item
, index
);
2527 * Insert elements into the group
2530 * @param {OO.ui.Element} itemWidget Item to insert
2531 * @param {number} index Insertion index
2533 OO
.ui
.mixin
.GroupElement
.prototype.insertItemElements = function ( itemWidget
, index
) {
2534 if ( index
=== undefined || index
< 0 || index
>= this.items
.length
) {
2535 this.$group
.append( itemWidget
.$element
);
2536 } else if ( index
=== 0 ) {
2537 this.$group
.prepend( itemWidget
.$element
);
2539 this.items
[ index
].$element
.before( itemWidget
.$element
);
2544 * Remove the specified items from a group.
2546 * Removed items are detached (not removed) from the DOM so that they may be reused.
2547 * To remove all items from a group, you may wish to use the #clearItems method instead.
2549 * @param {OO.ui.Element[]} items An array of items to remove
2552 OO
.ui
.mixin
.GroupElement
.prototype.removeItems = function ( items
) {
2553 var i
, len
, item
, index
;
2555 // Remove specific items elements
2556 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
2558 index
= this.items
.indexOf( item
);
2559 if ( index
!== -1 ) {
2560 item
.setElementGroup( null );
2561 item
.$element
.detach();
2566 OO
.EmitterList
.prototype.removeItems
.call( this, items
);
2568 this.emit( 'change', this.getItems() );
2573 * Clear all items from the group.
2575 * Cleared items are detached from the DOM, not removed, so that they may be reused.
2576 * To remove only a subset of items from a group, use the #removeItems method.
2580 OO
.ui
.mixin
.GroupElement
.prototype.clearItems = function () {
2583 // Remove all item elements
2584 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2585 this.items
[ i
].setElementGroup( null );
2586 this.items
[ i
].$element
.detach();
2590 OO
.EmitterList
.prototype.clearItems
.call( this );
2592 this.emit( 'change', this.getItems() );
2597 * LabelElement is often mixed into other classes to generate a label, which
2598 * helps identify the function of an interface element.
2599 * See the [OOUI documentation on MediaWiki] [1] for more information.
2601 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Labels
2607 * @param {Object} [config] Configuration options
2608 * @cfg {jQuery} [$label] The label element created by the class. If this
2609 * configuration is omitted, the label element will use a generated `<span>`.
2610 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
2611 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
2612 * in the future. See the [OOUI documentation on MediaWiki] [2] for examples.
2613 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Labels
2614 * @cfg {boolean} [invisibleLabel] Whether the label should be visually hidden (but still accessible
2615 * to screen-readers).
2617 OO
.ui
.mixin
.LabelElement
= function OoUiMixinLabelElement( config
) {
2618 // Configuration initialization
2619 config
= config
|| {};
2624 this.invisibleLabel
= null;
2627 this.setLabel( config
.label
|| this.constructor.static.label
);
2628 this.setLabelElement( config
.$label
|| $( '<span>' ) );
2629 this.setInvisibleLabel( config
.invisibleLabel
);
2634 OO
.initClass( OO
.ui
.mixin
.LabelElement
);
2639 * @event labelChange
2640 * @param {string} value
2643 /* Static Properties */
2646 * The label text. The label can be specified as a plaintext string, a function that will
2647 * produce a string in the future, or `null` for no label. The static value will
2648 * be overridden if a label is specified with the #label config option.
2652 * @property {string|Function|null}
2654 OO
.ui
.mixin
.LabelElement
.static.label
= null;
2656 /* Static methods */
2659 * Highlight the first occurrence of the query in the given text
2661 * @param {string} text Text
2662 * @param {string} query Query to find
2663 * @param {Function} [compare] Optional string comparator, e.g. Intl.Collator().compare
2664 * @return {jQuery} Text with the first match of the query
2665 * sub-string wrapped in highlighted span
2667 OO
.ui
.mixin
.LabelElement
.static.highlightQuery = function ( text
, query
, compare
) {
2670 $result
= $( '<span>' );
2674 qLen
= query
.length
;
2675 for ( i
= 0; offset
=== -1 && i
<= tLen
- qLen
; i
++ ) {
2676 if ( compare( query
, text
.slice( i
, i
+ qLen
) ) === 0 ) {
2681 offset
= text
.toLowerCase().indexOf( query
.toLowerCase() );
2684 if ( !query
.length
|| offset
=== -1 ) {
2685 $result
.text( text
);
2688 document
.createTextNode( text
.slice( 0, offset
) ),
2690 .addClass( 'oo-ui-labelElement-label-highlight' )
2691 .text( text
.slice( offset
, offset
+ query
.length
) ),
2692 document
.createTextNode( text
.slice( offset
+ query
.length
) )
2695 return $result
.contents();
2701 * Set the label element.
2703 * If an element is already set, it will be cleaned up before setting up the new element.
2705 * @param {jQuery} $label Element to use as label
2707 OO
.ui
.mixin
.LabelElement
.prototype.setLabelElement = function ( $label
) {
2708 if ( this.$label
) {
2709 this.$label
.removeClass( 'oo-ui-labelElement-label' ).empty();
2712 this.$label
= $label
.addClass( 'oo-ui-labelElement-label' );
2713 this.setLabelContent( this.label
);
2719 * An empty string will result in the label being hidden. A string containing only whitespace will
2720 * be converted to a single ` `.
2722 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
2723 * text; or null for no label
2726 OO
.ui
.mixin
.LabelElement
.prototype.setLabel = function ( label
) {
2727 label
= typeof label
=== 'function' ? OO
.ui
.resolveMsg( label
) : label
;
2728 label
= ( ( typeof label
=== 'string' || label
instanceof jQuery
) && label
.length
) || ( label
instanceof OO
.ui
.HtmlSnippet
&& label
.toString().length
) ? label
: null;
2730 if ( this.label
!== label
) {
2731 if ( this.$label
) {
2732 this.setLabelContent( label
);
2735 this.emit( 'labelChange' );
2738 this.$element
.toggleClass( 'oo-ui-labelElement', !!this.label
&& !this.invisibleLabel
);
2744 * Set whether the label should be visually hidden (but still accessible to screen-readers).
2746 * @param {boolean} invisibleLabel
2749 OO
.ui
.mixin
.LabelElement
.prototype.setInvisibleLabel = function ( invisibleLabel
) {
2750 invisibleLabel
= !!invisibleLabel
;
2752 if ( this.invisibleLabel
!== invisibleLabel
) {
2753 this.invisibleLabel
= invisibleLabel
;
2754 this.emit( 'labelChange' );
2757 this.$label
.toggleClass( 'oo-ui-labelElement-invisible', this.invisibleLabel
);
2758 // Pretend that there is no label, a lot of CSS has been written with this assumption
2759 this.$element
.toggleClass( 'oo-ui-labelElement', !!this.label
&& !this.invisibleLabel
);
2765 * Set the label as plain text with a highlighted query
2767 * @param {string} text Text label to set
2768 * @param {string} query Substring of text to highlight
2769 * @param {Function} [compare] Optional string comparator, e.g. Intl.Collator().compare
2772 OO
.ui
.mixin
.LabelElement
.prototype.setHighlightedQuery = function ( text
, query
, compare
) {
2773 return this.setLabel( this.constructor.static.highlightQuery( text
, query
, compare
) );
2779 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
2780 * text; or null for no label
2782 OO
.ui
.mixin
.LabelElement
.prototype.getLabel = function () {
2787 * Set the content of the label.
2789 * Do not call this method until after the label element has been set by #setLabelElement.
2792 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
2793 * text; or null for no label
2795 OO
.ui
.mixin
.LabelElement
.prototype.setLabelContent = function ( label
) {
2796 if ( typeof label
=== 'string' ) {
2797 if ( label
.match( /^\s*$/ ) ) {
2798 // Convert whitespace only string to a single non-breaking space
2799 this.$label
.html( ' ' );
2801 this.$label
.text( label
);
2803 } else if ( label
instanceof OO
.ui
.HtmlSnippet
) {
2804 this.$label
.html( label
.toString() );
2805 } else if ( label
instanceof jQuery
) {
2806 this.$label
.empty().append( label
);
2808 this.$label
.empty();
2813 * IconElement is often mixed into other classes to generate an icon.
2814 * Icons are graphics, about the size of normal text. They are used to aid the user
2815 * in locating a control or to convey information in a space-efficient way. See the
2816 * [OOUI documentation on MediaWiki] [1] for a list of icons
2817 * included in the library.
2819 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
2825 * @param {Object} [config] Configuration options
2826 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
2827 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
2828 * the icon element be set to an existing icon instead of the one generated by this class, set a
2829 * value using a jQuery selection. For example:
2831 * // Use a <div> tag instead of a <span>
2833 * // Use an existing icon element instead of the one generated by the class
2834 * $icon: this.$element
2835 * // Use an icon element from a child widget
2836 * $icon: this.childwidget.$element
2837 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
2838 * symbolic names. A map is used for i18n purposes and contains a `default` icon
2839 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
2840 * by the user's language.
2842 * Example of an i18n map:
2844 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2845 * See the [OOUI documentation on MediaWiki] [2] for a list of icons included in the library.
2846 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
2847 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
2848 * text. The icon title is displayed when users move the mouse over the icon.
2850 OO
.ui
.mixin
.IconElement
= function OoUiMixinIconElement( config
) {
2851 // Configuration initialization
2852 config
= config
|| {};
2857 this.iconTitle
= null;
2860 this.setIcon( config
.icon
|| this.constructor.static.icon
);
2861 this.setIconTitle( config
.iconTitle
|| this.constructor.static.iconTitle
);
2862 this.setIconElement( config
.$icon
|| $( '<span>' ) );
2867 OO
.initClass( OO
.ui
.mixin
.IconElement
);
2869 /* Static Properties */
2872 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
2873 * for i18n purposes and contains a `default` icon name and additional names keyed by
2874 * language code. The `default` name is used when no icon is keyed by the user's language.
2876 * Example of an i18n map:
2878 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2880 * Note: the static property will be overridden if the #icon configuration is used.
2884 * @property {Object|string}
2886 OO
.ui
.mixin
.IconElement
.static.icon
= null;
2889 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
2890 * function that returns title text, or `null` for no title.
2892 * The static property will be overridden if the #iconTitle configuration is used.
2896 * @property {string|Function|null}
2898 OO
.ui
.mixin
.IconElement
.static.iconTitle
= null;
2903 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
2904 * applies to the specified icon element instead of the one created by the class. If an icon
2905 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
2906 * and mixin methods will no longer affect the element.
2908 * @param {jQuery} $icon Element to use as icon
2910 OO
.ui
.mixin
.IconElement
.prototype.setIconElement = function ( $icon
) {
2913 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon
)
2914 .removeAttr( 'title' );
2918 .addClass( 'oo-ui-iconElement-icon' )
2919 .toggleClass( 'oo-ui-iconElement-noIcon', !this.icon
)
2920 .toggleClass( 'oo-ui-icon-' + this.icon
, !!this.icon
);
2921 if ( this.iconTitle
!== null ) {
2922 this.$icon
.attr( 'title', this.iconTitle
);
2925 this.updateThemeClasses();
2929 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
2930 * The icon parameter can also be set to a map of icon names. See the #icon config setting
2933 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
2934 * by language code, or `null` to remove the icon.
2937 OO
.ui
.mixin
.IconElement
.prototype.setIcon = function ( icon
) {
2938 icon
= OO
.isPlainObject( icon
) ? OO
.ui
.getLocalValue( icon
, null, 'default' ) : icon
;
2939 icon
= typeof icon
=== 'string' && icon
.trim().length
? icon
.trim() : null;
2941 if ( this.icon
!== icon
) {
2943 if ( this.icon
!== null ) {
2944 this.$icon
.removeClass( 'oo-ui-icon-' + this.icon
);
2946 if ( icon
!== null ) {
2947 this.$icon
.addClass( 'oo-ui-icon-' + icon
);
2953 this.$element
.toggleClass( 'oo-ui-iconElement', !!this.icon
);
2955 this.$icon
.toggleClass( 'oo-ui-iconElement-noIcon', !this.icon
);
2957 this.updateThemeClasses();
2963 * Set the icon title. Use `null` to remove the title.
2965 * @param {string|Function|null} iconTitle A text string used as the icon title,
2966 * a function that returns title text, or `null` for no title.
2969 OO
.ui
.mixin
.IconElement
.prototype.setIconTitle = function ( iconTitle
) {
2971 ( typeof iconTitle
=== 'function' || ( typeof iconTitle
=== 'string' && iconTitle
.length
) ) ?
2972 OO
.ui
.resolveMsg( iconTitle
) : null;
2974 if ( this.iconTitle
!== iconTitle
) {
2975 this.iconTitle
= iconTitle
;
2977 if ( this.iconTitle
!== null ) {
2978 this.$icon
.attr( 'title', iconTitle
);
2980 this.$icon
.removeAttr( 'title' );
2989 * Get the symbolic name of the icon.
2991 * @return {string} Icon name
2993 OO
.ui
.mixin
.IconElement
.prototype.getIcon = function () {
2998 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
3000 * @return {string} Icon title text
3002 OO
.ui
.mixin
.IconElement
.prototype.getIconTitle = function () {
3003 return this.iconTitle
;
3007 * IndicatorElement is often mixed into other classes to generate an indicator.
3008 * Indicators are small graphics that are generally used in two ways:
3010 * - To draw attention to the status of an item. For example, an indicator might be
3011 * used to show that an item in a list has errors that need to be resolved.
3012 * - To clarify the function of a control that acts in an exceptional way (a button
3013 * that opens a menu instead of performing an action directly, for example).
3015 * For a list of indicators included in the library, please see the
3016 * [OOUI documentation on MediaWiki] [1].
3018 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
3024 * @param {Object} [config] Configuration options
3025 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
3026 * configuration is omitted, the indicator element will use a generated `<span>`.
3027 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘clear’ or ‘down’).
3028 * See the [OOUI documentation on MediaWiki][2] for a list of indicators included
3030 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
3031 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
3032 * or a function that returns title text. The indicator title is displayed when users move
3033 * the mouse over the indicator.
3035 OO
.ui
.mixin
.IndicatorElement
= function OoUiMixinIndicatorElement( config
) {
3036 // Configuration initialization
3037 config
= config
|| {};
3040 this.$indicator
= null;
3041 this.indicator
= null;
3042 this.indicatorTitle
= null;
3045 this.setIndicator( config
.indicator
|| this.constructor.static.indicator
);
3046 this.setIndicatorTitle( config
.indicatorTitle
|| this.constructor.static.indicatorTitle
);
3047 this.setIndicatorElement( config
.$indicator
|| $( '<span>' ) );
3052 OO
.initClass( OO
.ui
.mixin
.IndicatorElement
);
3054 /* Static Properties */
3057 * Symbolic name of the indicator (e.g., ‘clear’ or ‘down’).
3058 * The static property will be overridden if the #indicator configuration is used.
3062 * @property {string|null}
3064 OO
.ui
.mixin
.IndicatorElement
.static.indicator
= null;
3067 * A text string used as the indicator title, a function that returns title text, or `null`
3068 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
3072 * @property {string|Function|null}
3074 OO
.ui
.mixin
.IndicatorElement
.static.indicatorTitle
= null;
3079 * Set the indicator element.
3081 * If an element is already set, it will be cleaned up before setting up the new element.
3083 * @param {jQuery} $indicator Element to use as indicator
3085 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorElement = function ( $indicator
) {
3086 if ( this.$indicator
) {
3088 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator
)
3089 .removeAttr( 'title' );
3092 this.$indicator
= $indicator
3093 .addClass( 'oo-ui-indicatorElement-indicator' )
3094 .toggleClass( 'oo-ui-indicatorElement-noIndicator', !this.indicator
)
3095 .toggleClass( 'oo-ui-indicator-' + this.indicator
, !!this.indicator
);
3096 if ( this.indicatorTitle
!== null ) {
3097 this.$indicator
.attr( 'title', this.indicatorTitle
);
3100 this.updateThemeClasses();
3104 * Set the indicator by its symbolic name: ‘clear’, ‘down’, ‘required’, ‘search’, ‘up’. Use `null` to remove the indicator.
3106 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
3109 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicator = function ( indicator
) {
3110 indicator
= typeof indicator
=== 'string' && indicator
.length
? indicator
.trim() : null;
3112 if ( this.indicator
!== indicator
) {
3113 if ( this.$indicator
) {
3114 if ( this.indicator
!== null ) {
3115 this.$indicator
.removeClass( 'oo-ui-indicator-' + this.indicator
);
3117 if ( indicator
!== null ) {
3118 this.$indicator
.addClass( 'oo-ui-indicator-' + indicator
);
3121 this.indicator
= indicator
;
3124 this.$element
.toggleClass( 'oo-ui-indicatorElement', !!this.indicator
);
3125 if ( this.$indicator
) {
3126 this.$indicator
.toggleClass( 'oo-ui-indicatorElement-noIndicator', !this.indicator
);
3128 this.updateThemeClasses();
3134 * Set the indicator title.
3136 * The title is displayed when a user moves the mouse over the indicator.
3138 * @param {string|Function|null} indicatorTitle Indicator title text, a function that returns text, or
3139 * `null` for no indicator title
3142 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorTitle = function ( indicatorTitle
) {
3144 ( typeof indicatorTitle
=== 'function' || ( typeof indicatorTitle
=== 'string' && indicatorTitle
.length
) ) ?
3145 OO
.ui
.resolveMsg( indicatorTitle
) : null;
3147 if ( this.indicatorTitle
!== indicatorTitle
) {
3148 this.indicatorTitle
= indicatorTitle
;
3149 if ( this.$indicator
) {
3150 if ( this.indicatorTitle
!== null ) {
3151 this.$indicator
.attr( 'title', indicatorTitle
);
3153 this.$indicator
.removeAttr( 'title' );
3162 * Get the symbolic name of the indicator (e.g., ‘clear’ or ‘down’).
3164 * @return {string} Symbolic name of indicator
3166 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicator = function () {
3167 return this.indicator
;
3171 * Get the indicator title.
3173 * The title is displayed when a user moves the mouse over the indicator.
3175 * @return {string} Indicator title text
3177 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicatorTitle = function () {
3178 return this.indicatorTitle
;
3182 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
3183 * additional functionality to an element created by another class. The class provides
3184 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
3185 * which are used to customize the look and feel of a widget to better describe its
3186 * importance and functionality.
3188 * The library currently contains the following styling flags for general use:
3190 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
3191 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
3193 * The flags affect the appearance of the buttons:
3196 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
3197 * var button1 = new OO.ui.ButtonWidget( {
3198 * label: 'Progressive',
3199 * flags: 'progressive'
3201 * var button2 = new OO.ui.ButtonWidget( {
3202 * label: 'Destructive',
3203 * flags: 'destructive'
3205 * $( 'body' ).append( button1.$element, button2.$element );
3207 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
3208 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
3210 * [1]: https://www.mediawiki.org/wiki/OOUI/Elements/Flagged
3216 * @param {Object} [config] Configuration options
3217 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'progressive' or 'primary') to apply.
3218 * Please see the [OOUI documentation on MediaWiki] [2] for more information about available flags.
3219 * [2]: https://www.mediawiki.org/wiki/OOUI/Elements/Flagged
3220 * @cfg {jQuery} [$flagged] The flagged element. By default,
3221 * the flagged functionality is applied to the element created by the class ($element).
3222 * If a different element is specified, the flagged functionality will be applied to it instead.
3224 OO
.ui
.mixin
.FlaggedElement
= function OoUiMixinFlaggedElement( config
) {
3225 // Configuration initialization
3226 config
= config
|| {};
3230 this.$flagged
= null;
3233 this.setFlags( config
.flags
);
3234 this.setFlaggedElement( config
.$flagged
|| this.$element
);
3241 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
3242 * parameter contains the name of each modified flag and indicates whether it was
3245 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
3246 * that the flag was added, `false` that the flag was removed.
3252 * Set the flagged element.
3254 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
3255 * If an element is already set, the method will remove the mixin’s effect on that element.
3257 * @param {jQuery} $flagged Element that should be flagged
3259 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlaggedElement = function ( $flagged
) {
3260 var classNames
= Object
.keys( this.flags
).map( function ( flag
) {
3261 return 'oo-ui-flaggedElement-' + flag
;
3264 if ( this.$flagged
) {
3265 this.$flagged
.removeClass( classNames
);
3268 this.$flagged
= $flagged
.addClass( classNames
);
3272 * Check if the specified flag is set.
3274 * @param {string} flag Name of flag
3275 * @return {boolean} The flag is set
3277 OO
.ui
.mixin
.FlaggedElement
.prototype.hasFlag = function ( flag
) {
3278 // This may be called before the constructor, thus before this.flags is set
3279 return this.flags
&& ( flag
in this.flags
);
3283 * Get the names of all flags set.
3285 * @return {string[]} Flag names
3287 OO
.ui
.mixin
.FlaggedElement
.prototype.getFlags = function () {
3288 // This may be called before the constructor, thus before this.flags is set
3289 return Object
.keys( this.flags
|| {} );
3298 OO
.ui
.mixin
.FlaggedElement
.prototype.clearFlags = function () {
3299 var flag
, className
,
3302 classPrefix
= 'oo-ui-flaggedElement-';
3304 for ( flag
in this.flags
) {
3305 className
= classPrefix
+ flag
;
3306 changes
[ flag
] = false;
3307 delete this.flags
[ flag
];
3308 remove
.push( className
);
3311 if ( this.$flagged
) {
3312 this.$flagged
.removeClass( remove
);
3315 this.updateThemeClasses();
3316 this.emit( 'flag', changes
);
3322 * Add one or more flags.
3324 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
3325 * or an object keyed by flag name with a boolean value that indicates whether the flag should
3326 * be added (`true`) or removed (`false`).
3330 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlags = function ( flags
) {
3331 var i
, len
, flag
, className
,
3335 classPrefix
= 'oo-ui-flaggedElement-';
3337 if ( typeof flags
=== 'string' ) {
3338 className
= classPrefix
+ flags
;
3340 if ( !this.flags
[ flags
] ) {
3341 this.flags
[ flags
] = true;
3342 add
.push( className
);
3344 } else if ( Array
.isArray( flags
) ) {
3345 for ( i
= 0, len
= flags
.length
; i
< len
; i
++ ) {
3347 className
= classPrefix
+ flag
;
3349 if ( !this.flags
[ flag
] ) {
3350 changes
[ flag
] = true;
3351 this.flags
[ flag
] = true;
3352 add
.push( className
);
3355 } else if ( OO
.isPlainObject( flags
) ) {
3356 for ( flag
in flags
) {
3357 className
= classPrefix
+ flag
;
3358 if ( flags
[ flag
] ) {
3360 if ( !this.flags
[ flag
] ) {
3361 changes
[ flag
] = true;
3362 this.flags
[ flag
] = true;
3363 add
.push( className
);
3367 if ( this.flags
[ flag
] ) {
3368 changes
[ flag
] = false;
3369 delete this.flags
[ flag
];
3370 remove
.push( className
);
3376 if ( this.$flagged
) {
3379 .removeClass( remove
);
3382 this.updateThemeClasses();
3383 this.emit( 'flag', changes
);
3389 * TitledElement is mixed into other classes to provide a `title` attribute.
3390 * Titles are rendered by the browser and are made visible when the user moves
3391 * the mouse over the element. Titles are not visible on touch devices.
3394 * // TitledElement provides a 'title' attribute to the
3395 * // ButtonWidget class
3396 * var button = new OO.ui.ButtonWidget( {
3397 * label: 'Button with Title',
3398 * title: 'I am a button'
3400 * $( 'body' ).append( button.$element );
3406 * @param {Object} [config] Configuration options
3407 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
3408 * If this config is omitted, the title functionality is applied to $element, the
3409 * element created by the class.
3410 * @cfg {string|Function} [title] The title text or a function that returns text. If
3411 * this config is omitted, the value of the {@link #static-title static title} property is used.
3413 OO
.ui
.mixin
.TitledElement
= function OoUiMixinTitledElement( config
) {
3414 // Configuration initialization
3415 config
= config
|| {};
3418 this.$titled
= null;
3422 this.setTitle( config
.title
!== undefined ? config
.title
: this.constructor.static.title
);
3423 this.setTitledElement( config
.$titled
|| this.$element
);
3428 OO
.initClass( OO
.ui
.mixin
.TitledElement
);
3430 /* Static Properties */
3433 * The title text, a function that returns text, or `null` for no title. The value of the static property
3434 * is overridden if the #title config option is used.
3438 * @property {string|Function|null}
3440 OO
.ui
.mixin
.TitledElement
.static.title
= null;
3445 * Set the titled element.
3447 * This method is used to retarget a TitledElement mixin so that its functionality applies to the specified element.
3448 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
3450 * @param {jQuery} $titled Element that should use the 'titled' functionality
3452 OO
.ui
.mixin
.TitledElement
.prototype.setTitledElement = function ( $titled
) {
3453 if ( this.$titled
) {
3454 this.$titled
.removeAttr( 'title' );
3457 this.$titled
= $titled
;
3466 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
3469 OO
.ui
.mixin
.TitledElement
.prototype.setTitle = function ( title
) {
3470 title
= typeof title
=== 'function' ? OO
.ui
.resolveMsg( title
) : title
;
3471 title
= ( typeof title
=== 'string' && title
.length
) ? title
: null;
3473 if ( this.title
!== title
) {
3482 * Update the title attribute, in case of changes to title or accessKey.
3487 OO
.ui
.mixin
.TitledElement
.prototype.updateTitle = function () {
3488 var title
= this.getTitle();
3489 if ( this.$titled
) {
3490 if ( title
!== null ) {
3491 // Only if this is an AccessKeyedElement
3492 if ( this.formatTitleWithAccessKey
) {
3493 title
= this.formatTitleWithAccessKey( title
);
3495 this.$titled
.attr( 'title', title
);
3497 this.$titled
.removeAttr( 'title' );
3506 * @return {string} Title string
3508 OO
.ui
.mixin
.TitledElement
.prototype.getTitle = function () {
3513 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
3514 * Accesskeys allow an user to go to a specific element by using
3515 * a shortcut combination of a browser specific keys + the key
3519 * // AccessKeyedElement provides an 'accesskey' attribute to the
3520 * // ButtonWidget class
3521 * var button = new OO.ui.ButtonWidget( {
3522 * label: 'Button with Accesskey',
3525 * $( 'body' ).append( button.$element );
3531 * @param {Object} [config] Configuration options
3532 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
3533 * If this config is omitted, the accesskey functionality is applied to $element, the
3534 * element created by the class.
3535 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
3536 * this config is omitted, no accesskey will be added.
3538 OO
.ui
.mixin
.AccessKeyedElement
= function OoUiMixinAccessKeyedElement( config
) {
3539 // Configuration initialization
3540 config
= config
|| {};
3543 this.$accessKeyed
= null;
3544 this.accessKey
= null;
3547 this.setAccessKey( config
.accessKey
|| null );
3548 this.setAccessKeyedElement( config
.$accessKeyed
|| this.$element
);
3550 // If this is also a TitledElement and it initialized before we did, we may have
3551 // to update the title with the access key
3552 if ( this.updateTitle
) {
3559 OO
.initClass( OO
.ui
.mixin
.AccessKeyedElement
);
3561 /* Static Properties */
3564 * The access key, a function that returns a key, or `null` for no accesskey.
3568 * @property {string|Function|null}
3570 OO
.ui
.mixin
.AccessKeyedElement
.static.accessKey
= null;
3575 * Set the accesskeyed element.
3577 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
3578 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
3580 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyed' functionality
3582 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKeyedElement = function ( $accessKeyed
) {
3583 if ( this.$accessKeyed
) {
3584 this.$accessKeyed
.removeAttr( 'accesskey' );
3587 this.$accessKeyed
= $accessKeyed
;
3588 if ( this.accessKey
) {
3589 this.$accessKeyed
.attr( 'accesskey', this.accessKey
);
3596 * @param {string|Function|null} accessKey Key, a function that returns a key, or `null` for no accesskey
3599 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKey = function ( accessKey
) {
3600 accessKey
= typeof accessKey
=== 'string' ? OO
.ui
.resolveMsg( accessKey
) : null;
3602 if ( this.accessKey
!== accessKey
) {
3603 if ( this.$accessKeyed
) {
3604 if ( accessKey
!== null ) {
3605 this.$accessKeyed
.attr( 'accesskey', accessKey
);
3607 this.$accessKeyed
.removeAttr( 'accesskey' );
3610 this.accessKey
= accessKey
;
3612 // Only if this is a TitledElement
3613 if ( this.updateTitle
) {
3624 * @return {string} accessKey string
3626 OO
.ui
.mixin
.AccessKeyedElement
.prototype.getAccessKey = function () {
3627 return this.accessKey
;
3631 * Add information about the access key to the element's tooltip label.
3632 * (This is only public for hacky usage in FieldLayout.)
3634 * @param {string} title Tooltip label for `title` attribute
3637 OO
.ui
.mixin
.AccessKeyedElement
.prototype.formatTitleWithAccessKey = function ( title
) {
3640 if ( !this.$accessKeyed
) {
3641 // Not initialized yet; the constructor will call updateTitle() which will rerun this function
3644 // Use jquery.accessKeyLabel if available to show modifiers, otherwise just display the single key
3645 if ( $.fn
.updateTooltipAccessKeys
&& $.fn
.updateTooltipAccessKeys
.getAccessKeyLabel
) {
3646 accessKey
= $.fn
.updateTooltipAccessKeys
.getAccessKeyLabel( this.$accessKeyed
[ 0 ] );
3648 accessKey
= this.getAccessKey();
3651 title
+= ' [' + accessKey
+ ']';
3657 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
3658 * feels, and functionality can be customized via the class’s configuration options
3659 * and methods. Please see the [OOUI documentation on MediaWiki] [1] for more information
3662 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches
3665 * // A button widget
3666 * var button = new OO.ui.ButtonWidget( {
3667 * label: 'Button with Icon',
3671 * $( 'body' ).append( button.$element );
3673 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
3676 * @extends OO.ui.Widget
3677 * @mixins OO.ui.mixin.ButtonElement
3678 * @mixins OO.ui.mixin.IconElement
3679 * @mixins OO.ui.mixin.IndicatorElement
3680 * @mixins OO.ui.mixin.LabelElement
3681 * @mixins OO.ui.mixin.TitledElement
3682 * @mixins OO.ui.mixin.FlaggedElement
3683 * @mixins OO.ui.mixin.TabIndexedElement
3684 * @mixins OO.ui.mixin.AccessKeyedElement
3687 * @param {Object} [config] Configuration options
3688 * @cfg {boolean} [active=false] Whether button should be shown as active
3689 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
3690 * @cfg {string} [target] The frame or window in which to open the hyperlink.
3691 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
3693 OO
.ui
.ButtonWidget
= function OoUiButtonWidget( config
) {
3694 // Configuration initialization
3695 config
= config
|| {};
3697 // Parent constructor
3698 OO
.ui
.ButtonWidget
.parent
.call( this, config
);
3700 // Mixin constructors
3701 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
3702 OO
.ui
.mixin
.IconElement
.call( this, config
);
3703 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
3704 OO
.ui
.mixin
.LabelElement
.call( this, config
);
3705 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
3706 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
3707 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
3708 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$button
} ) );
3713 this.noFollow
= false;
3716 this.connect( this, { disable
: 'onDisable' } );
3719 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
3721 .addClass( 'oo-ui-buttonWidget' )
3722 .append( this.$button
);
3723 this.setActive( config
.active
);
3724 this.setHref( config
.href
);
3725 this.setTarget( config
.target
);
3726 this.setNoFollow( config
.noFollow
);
3731 OO
.inheritClass( OO
.ui
.ButtonWidget
, OO
.ui
.Widget
);
3732 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
3733 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IconElement
);
3734 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
3735 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.LabelElement
);
3736 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TitledElement
);
3737 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
3738 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
3739 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
3741 /* Static Properties */
3747 OO
.ui
.ButtonWidget
.static.cancelButtonMouseDownEvents
= false;
3753 OO
.ui
.ButtonWidget
.static.tagName
= 'span';
3758 * Get hyperlink location.
3760 * @return {string} Hyperlink location
3762 OO
.ui
.ButtonWidget
.prototype.getHref = function () {
3767 * Get hyperlink target.
3769 * @return {string} Hyperlink target
3771 OO
.ui
.ButtonWidget
.prototype.getTarget = function () {
3776 * Get search engine traversal hint.
3778 * @return {boolean} Whether search engines should avoid traversing this hyperlink
3780 OO
.ui
.ButtonWidget
.prototype.getNoFollow = function () {
3781 return this.noFollow
;
3785 * Set hyperlink location.
3787 * @param {string|null} href Hyperlink location, null to remove
3789 OO
.ui
.ButtonWidget
.prototype.setHref = function ( href
) {
3790 href
= typeof href
=== 'string' ? href
: null;
3791 if ( href
!== null && !OO
.ui
.isSafeUrl( href
) ) {
3795 if ( href
!== this.href
) {
3804 * Update the `href` attribute, in case of changes to href or
3810 OO
.ui
.ButtonWidget
.prototype.updateHref = function () {
3811 if ( this.href
!== null && !this.isDisabled() ) {
3812 this.$button
.attr( 'href', this.href
);
3814 this.$button
.removeAttr( 'href' );
3821 * Handle disable events.
3824 * @param {boolean} disabled Element is disabled
3826 OO
.ui
.ButtonWidget
.prototype.onDisable = function () {
3831 * Set hyperlink target.
3833 * @param {string|null} target Hyperlink target, null to remove
3835 OO
.ui
.ButtonWidget
.prototype.setTarget = function ( target
) {
3836 target
= typeof target
=== 'string' ? target
: null;
3838 if ( target
!== this.target
) {
3839 this.target
= target
;
3840 if ( target
!== null ) {
3841 this.$button
.attr( 'target', target
);
3843 this.$button
.removeAttr( 'target' );
3851 * Set search engine traversal hint.
3853 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
3855 OO
.ui
.ButtonWidget
.prototype.setNoFollow = function ( noFollow
) {
3856 noFollow
= typeof noFollow
=== 'boolean' ? noFollow
: true;
3858 if ( noFollow
!== this.noFollow
) {
3859 this.noFollow
= noFollow
;
3861 this.$button
.attr( 'rel', 'nofollow' );
3863 this.$button
.removeAttr( 'rel' );
3870 // Override method visibility hints from ButtonElement
3881 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
3882 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
3883 * removed, and cleared from the group.
3886 * // Example: A ButtonGroupWidget with two buttons
3887 * var button1 = new OO.ui.PopupButtonWidget( {
3888 * label: 'Select a category',
3891 * $content: $( '<p>List of categories...</p>' ),
3896 * var button2 = new OO.ui.ButtonWidget( {
3899 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
3900 * items: [button1, button2]
3902 * $( 'body' ).append( buttonGroup.$element );
3905 * @extends OO.ui.Widget
3906 * @mixins OO.ui.mixin.GroupElement
3909 * @param {Object} [config] Configuration options
3910 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
3912 OO
.ui
.ButtonGroupWidget
= function OoUiButtonGroupWidget( config
) {
3913 // Configuration initialization
3914 config
= config
|| {};
3916 // Parent constructor
3917 OO
.ui
.ButtonGroupWidget
.parent
.call( this, config
);
3919 // Mixin constructors
3920 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
3923 this.$element
.addClass( 'oo-ui-buttonGroupWidget' );
3924 if ( Array
.isArray( config
.items
) ) {
3925 this.addItems( config
.items
);
3931 OO
.inheritClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.Widget
);
3932 OO
.mixinClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.mixin
.GroupElement
);
3934 /* Static Properties */
3940 OO
.ui
.ButtonGroupWidget
.static.tagName
= 'span';
3949 OO
.ui
.ButtonGroupWidget
.prototype.focus = function () {
3950 if ( !this.isDisabled() ) {
3951 if ( this.items
[ 0 ] ) {
3952 this.items
[ 0 ].focus();
3961 OO
.ui
.ButtonGroupWidget
.prototype.simulateLabelClick = function () {
3966 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
3967 * which creates a label that identifies the icon’s function. See the [OOUI documentation on MediaWiki] [1]
3968 * for a list of icons included in the library.
3971 * // An icon widget with a label
3972 * var myIcon = new OO.ui.IconWidget( {
3976 * // Create a label.
3977 * var iconLabel = new OO.ui.LabelWidget( {
3980 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
3982 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
3985 * @extends OO.ui.Widget
3986 * @mixins OO.ui.mixin.IconElement
3987 * @mixins OO.ui.mixin.TitledElement
3988 * @mixins OO.ui.mixin.LabelElement
3989 * @mixins OO.ui.mixin.FlaggedElement
3992 * @param {Object} [config] Configuration options
3994 OO
.ui
.IconWidget
= function OoUiIconWidget( config
) {
3995 // Configuration initialization
3996 config
= config
|| {};
3998 // Parent constructor
3999 OO
.ui
.IconWidget
.parent
.call( this, config
);
4001 // Mixin constructors
4002 OO
.ui
.mixin
.IconElement
.call( this, $.extend( {}, config
, { $icon
: this.$element
} ) );
4003 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
4004 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
, invisibleLabel
: true } ) );
4005 OO
.ui
.mixin
.FlaggedElement
.call( this, $.extend( {}, config
, { $flagged
: this.$element
} ) );
4008 this.$element
.addClass( 'oo-ui-iconWidget' );
4009 // Remove class added by LabelElement initialization. It causes unexpected CSS to apply when
4010 // nested in other widgets, because this widget used to not mix in LabelElement.
4011 this.$element
.removeClass( 'oo-ui-labelElement-label' );
4016 OO
.inheritClass( OO
.ui
.IconWidget
, OO
.ui
.Widget
);
4017 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.IconElement
);
4018 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.TitledElement
);
4019 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.LabelElement
);
4020 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.FlaggedElement
);
4022 /* Static Properties */
4028 OO
.ui
.IconWidget
.static.tagName
= 'span';
4031 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
4032 * attention to the status of an item or to clarify the function within a control. For a list of
4033 * indicators included in the library, please see the [OOUI documentation on MediaWiki][1].
4036 * // Example of an indicator widget
4037 * var indicator1 = new OO.ui.IndicatorWidget( {
4038 * indicator: 'required'
4041 * // Create a fieldset layout to add a label
4042 * var fieldset = new OO.ui.FieldsetLayout();
4043 * fieldset.addItems( [
4044 * new OO.ui.FieldLayout( indicator1, { label: 'A required indicator:' } )
4046 * $( 'body' ).append( fieldset.$element );
4048 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
4051 * @extends OO.ui.Widget
4052 * @mixins OO.ui.mixin.IndicatorElement
4053 * @mixins OO.ui.mixin.TitledElement
4054 * @mixins OO.ui.mixin.LabelElement
4057 * @param {Object} [config] Configuration options
4059 OO
.ui
.IndicatorWidget
= function OoUiIndicatorWidget( config
) {
4060 // Configuration initialization
4061 config
= config
|| {};
4063 // Parent constructor
4064 OO
.ui
.IndicatorWidget
.parent
.call( this, config
);
4066 // Mixin constructors
4067 OO
.ui
.mixin
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$element
} ) );
4068 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
4069 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
, invisibleLabel
: true } ) );
4072 this.$element
.addClass( 'oo-ui-indicatorWidget' );
4073 // Remove class added by LabelElement initialization. It causes unexpected CSS to apply when
4074 // nested in other widgets, because this widget used to not mix in LabelElement.
4075 this.$element
.removeClass( 'oo-ui-labelElement-label' );
4080 OO
.inheritClass( OO
.ui
.IndicatorWidget
, OO
.ui
.Widget
);
4081 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.IndicatorElement
);
4082 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.TitledElement
);
4083 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.LabelElement
);
4085 /* Static Properties */
4091 OO
.ui
.IndicatorWidget
.static.tagName
= 'span';
4094 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
4095 * be configured with a `label` option that is set to a string, a label node, or a function:
4097 * - String: a plaintext string
4098 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
4099 * label that includes a link or special styling, such as a gray color or additional graphical elements.
4100 * - Function: a function that will produce a string in the future. Functions are used
4101 * in cases where the value of the label is not currently defined.
4103 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
4104 * will come into focus when the label is clicked.
4107 * // Examples of LabelWidgets
4108 * var label1 = new OO.ui.LabelWidget( {
4109 * label: 'plaintext label'
4111 * var label2 = new OO.ui.LabelWidget( {
4112 * label: $( '<a href="default.html">jQuery label</a>' )
4114 * // Create a fieldset layout with fields for each example
4115 * var fieldset = new OO.ui.FieldsetLayout();
4116 * fieldset.addItems( [
4117 * new OO.ui.FieldLayout( label1 ),
4118 * new OO.ui.FieldLayout( label2 )
4120 * $( 'body' ).append( fieldset.$element );
4123 * @extends OO.ui.Widget
4124 * @mixins OO.ui.mixin.LabelElement
4125 * @mixins OO.ui.mixin.TitledElement
4128 * @param {Object} [config] Configuration options
4129 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
4130 * Clicking the label will focus the specified input field.
4132 OO
.ui
.LabelWidget
= function OoUiLabelWidget( config
) {
4133 // Configuration initialization
4134 config
= config
|| {};
4136 // Parent constructor
4137 OO
.ui
.LabelWidget
.parent
.call( this, config
);
4139 // Mixin constructors
4140 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
} ) );
4141 OO
.ui
.mixin
.TitledElement
.call( this, config
);
4144 this.input
= config
.input
;
4148 if ( this.input
.getInputId() ) {
4149 this.$element
.attr( 'for', this.input
.getInputId() );
4151 this.$label
.on( 'click', function () {
4152 this.input
.simulateLabelClick();
4156 this.$element
.addClass( 'oo-ui-labelWidget' );
4161 OO
.inheritClass( OO
.ui
.LabelWidget
, OO
.ui
.Widget
);
4162 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.LabelElement
);
4163 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.TitledElement
);
4165 /* Static Properties */
4171 OO
.ui
.LabelWidget
.static.tagName
= 'label';
4174 * PendingElement is a mixin that is used to create elements that notify users that something is happening
4175 * and that they should wait before proceeding. The pending state is visually represented with a pending
4176 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
4177 * field of a {@link OO.ui.TextInputWidget text input widget}.
4179 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
4180 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
4181 * in process dialogs.
4184 * function MessageDialog( config ) {
4185 * MessageDialog.parent.call( this, config );
4187 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
4189 * MessageDialog.static.name = 'myMessageDialog';
4190 * MessageDialog.static.actions = [
4191 * { action: 'save', label: 'Done', flags: 'primary' },
4192 * { label: 'Cancel', flags: 'safe' }
4195 * MessageDialog.prototype.initialize = function () {
4196 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
4197 * this.content = new OO.ui.PanelLayout( { padded: true } );
4198 * this.content.$element.append( '<p>Click the \'Done\' action widget to see its pending state. Note that action widgets can be marked pending in message dialogs but not process dialogs.</p>' );
4199 * this.$body.append( this.content.$element );
4201 * MessageDialog.prototype.getBodyHeight = function () {
4204 * MessageDialog.prototype.getActionProcess = function ( action ) {
4205 * var dialog = this;
4206 * if ( action === 'save' ) {
4207 * dialog.getActions().get({actions: 'save'})[0].pushPending();
4208 * return new OO.ui.Process()
4210 * .next( function () {
4211 * dialog.getActions().get({actions: 'save'})[0].popPending();
4214 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
4217 * var windowManager = new OO.ui.WindowManager();
4218 * $( 'body' ).append( windowManager.$element );
4220 * var dialog = new MessageDialog();
4221 * windowManager.addWindows( [ dialog ] );
4222 * windowManager.openWindow( dialog );
4228 * @param {Object} [config] Configuration options
4229 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
4231 OO
.ui
.mixin
.PendingElement
= function OoUiMixinPendingElement( config
) {
4232 // Configuration initialization
4233 config
= config
|| {};
4237 this.$pending
= null;
4240 this.setPendingElement( config
.$pending
|| this.$element
);
4245 OO
.initClass( OO
.ui
.mixin
.PendingElement
);
4250 * Set the pending element (and clean up any existing one).
4252 * @param {jQuery} $pending The element to set to pending.
4254 OO
.ui
.mixin
.PendingElement
.prototype.setPendingElement = function ( $pending
) {
4255 if ( this.$pending
) {
4256 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
4259 this.$pending
= $pending
;
4260 if ( this.pending
> 0 ) {
4261 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
4266 * Check if an element is pending.
4268 * @return {boolean} Element is pending
4270 OO
.ui
.mixin
.PendingElement
.prototype.isPending = function () {
4271 return !!this.pending
;
4275 * Increase the pending counter. The pending state will remain active until the counter is zero
4276 * (i.e., the number of calls to #pushPending and #popPending is the same).
4280 OO
.ui
.mixin
.PendingElement
.prototype.pushPending = function () {
4281 if ( this.pending
=== 0 ) {
4282 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
4283 this.updateThemeClasses();
4291 * Decrease the pending counter. The pending state will remain active until the counter is zero
4292 * (i.e., the number of calls to #pushPending and #popPending is the same).
4296 OO
.ui
.mixin
.PendingElement
.prototype.popPending = function () {
4297 if ( this.pending
=== 1 ) {
4298 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
4299 this.updateThemeClasses();
4301 this.pending
= Math
.max( 0, this.pending
- 1 );
4307 * Element that will stick adjacent to a specified container, even when it is inserted elsewhere
4308 * in the document (for example, in an OO.ui.Window's $overlay).
4310 * The elements's position is automatically calculated and maintained when window is resized or the
4311 * page is scrolled. If you reposition the container manually, you have to call #position to make
4312 * sure the element is still placed correctly.
4314 * As positioning is only possible when both the element and the container are attached to the DOM
4315 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
4316 * the #toggle method to display a floating popup, for example.
4322 * @param {Object} [config] Configuration options
4323 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
4324 * @cfg {jQuery} [$floatableContainer] Node to position adjacent to
4325 * @cfg {string} [verticalPosition='below'] Where to position $floatable vertically:
4326 * 'below': Directly below $floatableContainer, aligning f's top edge with fC's bottom edge
4327 * 'above': Directly above $floatableContainer, aligning f's bottom edge with fC's top edge
4328 * 'top': Align the top edge with $floatableContainer's top edge
4329 * 'bottom': Align the bottom edge with $floatableContainer's bottom edge
4330 * 'center': Vertically align the center with $floatableContainer's center
4331 * @cfg {string} [horizontalPosition='start'] Where to position $floatable horizontally:
4332 * 'before': Directly before $floatableContainer, aligning f's end edge with fC's start edge
4333 * 'after': Directly after $floatableContainer, aligning f's start edge with fC's end edge
4334 * 'start': Align the start (left in LTR, right in RTL) edge with $floatableContainer's start edge
4335 * 'end': Align the end (right in LTR, left in RTL) edge with $floatableContainer's end edge
4336 * 'center': Horizontally align the center with $floatableContainer's center
4337 * @cfg {boolean} [hideWhenOutOfView=true] Whether to hide the floatable element if the container
4340 OO
.ui
.mixin
.FloatableElement
= function OoUiMixinFloatableElement( config
) {
4341 // Configuration initialization
4342 config
= config
|| {};
4345 this.$floatable
= null;
4346 this.$floatableContainer
= null;
4347 this.$floatableWindow
= null;
4348 this.$floatableClosestScrollable
= null;
4349 this.floatableOutOfView
= false;
4350 this.onFloatableScrollHandler
= this.position
.bind( this );
4351 this.onFloatableWindowResizeHandler
= this.position
.bind( this );
4354 this.setFloatableContainer( config
.$floatableContainer
);
4355 this.setFloatableElement( config
.$floatable
|| this.$element
);
4356 this.setVerticalPosition( config
.verticalPosition
|| 'below' );
4357 this.setHorizontalPosition( config
.horizontalPosition
|| 'start' );
4358 this.hideWhenOutOfView
= config
.hideWhenOutOfView
=== undefined ? true : !!config
.hideWhenOutOfView
;
4364 * Set floatable element.
4366 * If an element is already set, it will be cleaned up before setting up the new element.
4368 * @param {jQuery} $floatable Element to make floatable
4370 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableElement = function ( $floatable
) {
4371 if ( this.$floatable
) {
4372 this.$floatable
.removeClass( 'oo-ui-floatableElement-floatable' );
4373 this.$floatable
.css( { left
: '', top
: '' } );
4376 this.$floatable
= $floatable
.addClass( 'oo-ui-floatableElement-floatable' );
4381 * Set floatable container.
4383 * The element will be positioned relative to the specified container.
4385 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
4387 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableContainer = function ( $floatableContainer
) {
4388 this.$floatableContainer
= $floatableContainer
;
4389 if ( this.$floatable
) {
4395 * Change how the element is positioned vertically.
4397 * @param {string} position 'below', 'above', 'top', 'bottom' or 'center'
4399 OO
.ui
.mixin
.FloatableElement
.prototype.setVerticalPosition = function ( position
) {
4400 if ( [ 'below', 'above', 'top', 'bottom', 'center' ].indexOf( position
) === -1 ) {
4401 throw new Error( 'Invalid value for vertical position: ' + position
);
4403 if ( this.verticalPosition
!== position
) {
4404 this.verticalPosition
= position
;
4405 if ( this.$floatable
) {
4412 * Change how the element is positioned horizontally.
4414 * @param {string} position 'before', 'after', 'start', 'end' or 'center'
4416 OO
.ui
.mixin
.FloatableElement
.prototype.setHorizontalPosition = function ( position
) {
4417 if ( [ 'before', 'after', 'start', 'end', 'center' ].indexOf( position
) === -1 ) {
4418 throw new Error( 'Invalid value for horizontal position: ' + position
);
4420 if ( this.horizontalPosition
!== position
) {
4421 this.horizontalPosition
= position
;
4422 if ( this.$floatable
) {
4429 * Toggle positioning.
4431 * Do not turn positioning on until after the element is attached to the DOM and visible.
4433 * @param {boolean} [positioning] Enable positioning, omit to toggle
4436 OO
.ui
.mixin
.FloatableElement
.prototype.togglePositioning = function ( positioning
) {
4437 var closestScrollableOfContainer
;
4439 if ( !this.$floatable
|| !this.$floatableContainer
) {
4443 positioning
= positioning
=== undefined ? !this.positioning
: !!positioning
;
4445 if ( positioning
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
4446 OO
.ui
.warnDeprecation( 'FloatableElement#togglePositioning: Before calling this method, the element must be attached to the DOM.' );
4447 this.warnedUnattached
= true;
4450 if ( this.positioning
!== positioning
) {
4451 this.positioning
= positioning
;
4453 closestScrollableOfContainer
= OO
.ui
.Element
.static.getClosestScrollableContainer( this.$floatableContainer
[ 0 ] );
4454 // If the scrollable is the root, we have to listen to scroll events
4455 // on the window because of browser inconsistencies.
4456 if ( $( closestScrollableOfContainer
).is( 'html, body' ) ) {
4457 closestScrollableOfContainer
= OO
.ui
.Element
.static.getWindow( closestScrollableOfContainer
);
4460 if ( positioning
) {
4461 this.$floatableWindow
= $( this.getElementWindow() );
4462 this.$floatableWindow
.on( 'resize', this.onFloatableWindowResizeHandler
);
4464 this.$floatableClosestScrollable
= $( closestScrollableOfContainer
);
4465 this.$floatableClosestScrollable
.on( 'scroll', this.onFloatableScrollHandler
);
4467 // Initial position after visible
4470 if ( this.$floatableWindow
) {
4471 this.$floatableWindow
.off( 'resize', this.onFloatableWindowResizeHandler
);
4472 this.$floatableWindow
= null;
4475 if ( this.$floatableClosestScrollable
) {
4476 this.$floatableClosestScrollable
.off( 'scroll', this.onFloatableScrollHandler
);
4477 this.$floatableClosestScrollable
= null;
4480 this.$floatable
.css( { left
: '', right
: '', top
: '' } );
4488 * Check whether the bottom edge of the given element is within the viewport of the given container.
4491 * @param {jQuery} $element
4492 * @param {jQuery} $container
4495 OO
.ui
.mixin
.FloatableElement
.prototype.isElementInViewport = function ( $element
, $container
) {
4496 var elemRect
, contRect
, topEdgeInBounds
, bottomEdgeInBounds
, leftEdgeInBounds
, rightEdgeInBounds
,
4497 startEdgeInBounds
, endEdgeInBounds
, viewportSpacing
,
4498 direction
= $element
.css( 'direction' );
4500 elemRect
= $element
[ 0 ].getBoundingClientRect();
4501 if ( $container
[ 0 ] === window
) {
4502 viewportSpacing
= OO
.ui
.getViewportSpacing();
4506 right
: document
.documentElement
.clientWidth
,
4507 bottom
: document
.documentElement
.clientHeight
4509 contRect
.top
+= viewportSpacing
.top
;
4510 contRect
.left
+= viewportSpacing
.left
;
4511 contRect
.right
-= viewportSpacing
.right
;
4512 contRect
.bottom
-= viewportSpacing
.bottom
;
4514 contRect
= $container
[ 0 ].getBoundingClientRect();
4517 topEdgeInBounds
= elemRect
.top
>= contRect
.top
&& elemRect
.top
<= contRect
.bottom
;
4518 bottomEdgeInBounds
= elemRect
.bottom
>= contRect
.top
&& elemRect
.bottom
<= contRect
.bottom
;
4519 leftEdgeInBounds
= elemRect
.left
>= contRect
.left
&& elemRect
.left
<= contRect
.right
;
4520 rightEdgeInBounds
= elemRect
.right
>= contRect
.left
&& elemRect
.right
<= contRect
.right
;
4521 if ( direction
=== 'rtl' ) {
4522 startEdgeInBounds
= rightEdgeInBounds
;
4523 endEdgeInBounds
= leftEdgeInBounds
;
4525 startEdgeInBounds
= leftEdgeInBounds
;
4526 endEdgeInBounds
= rightEdgeInBounds
;
4529 if ( this.verticalPosition
=== 'below' && !bottomEdgeInBounds
) {
4532 if ( this.verticalPosition
=== 'above' && !topEdgeInBounds
) {
4535 if ( this.horizontalPosition
=== 'before' && !startEdgeInBounds
) {
4538 if ( this.horizontalPosition
=== 'after' && !endEdgeInBounds
) {
4542 // The other positioning values are all about being inside the container,
4543 // so in those cases all we care about is that any part of the container is visible.
4544 return elemRect
.top
<= contRect
.bottom
&& elemRect
.bottom
>= contRect
.top
&&
4545 elemRect
.left
<= contRect
.right
&& elemRect
.right
>= contRect
.left
;
4549 * Check if the floatable is hidden to the user because it was offscreen.
4551 * @return {boolean} Floatable is out of view
4553 OO
.ui
.mixin
.FloatableElement
.prototype.isFloatableOutOfView = function () {
4554 return this.floatableOutOfView
;
4558 * Position the floatable below its container.
4560 * This should only be done when both of them are attached to the DOM and visible.
4564 OO
.ui
.mixin
.FloatableElement
.prototype.position = function () {
4565 if ( !this.positioning
) {
4570 // To continue, some things need to be true:
4571 // The element must actually be in the DOM
4572 this.isElementAttached() && (
4573 // The closest scrollable is the current window
4574 this.$floatableClosestScrollable
[ 0 ] === this.getElementWindow() ||
4575 // OR is an element in the element's DOM
4576 $.contains( this.getElementDocument(), this.$floatableClosestScrollable
[ 0 ] )
4579 // Abort early if important parts of the widget are no longer attached to the DOM
4583 this.floatableOutOfView
= this.hideWhenOutOfView
&& !this.isElementInViewport( this.$floatableContainer
, this.$floatableClosestScrollable
);
4584 if ( this.floatableOutOfView
) {
4585 this.$floatable
.addClass( 'oo-ui-element-hidden' );
4588 this.$floatable
.removeClass( 'oo-ui-element-hidden' );
4591 this.$floatable
.css( this.computePosition() );
4593 // We updated the position, so re-evaluate the clipping state.
4594 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
4595 // will not notice the need to update itself.)
4596 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
4597 // it not listen to the right events in the right places?
4606 * Compute how #$floatable should be positioned based on the position of #$floatableContainer
4607 * and the positioning settings. This is a helper for #position that shouldn't be called directly,
4608 * but may be overridden by subclasses if they want to change or add to the positioning logic.
4610 * @return {Object} New position to apply with .css(). Keys are 'top', 'left', 'bottom' and 'right'.
4612 OO
.ui
.mixin
.FloatableElement
.prototype.computePosition = function () {
4613 var isBody
, scrollableX
, scrollableY
, containerPos
,
4614 horizScrollbarHeight
, vertScrollbarWidth
, scrollTop
, scrollLeft
,
4615 newPos
= { top
: '', left
: '', bottom
: '', right
: '' },
4616 direction
= this.$floatableContainer
.css( 'direction' ),
4617 $offsetParent
= this.$floatable
.offsetParent();
4619 if ( $offsetParent
.is( 'html' ) ) {
4620 // The innerHeight/Width and clientHeight/Width calculations don't work well on the
4621 // <html> element, but they do work on the <body>
4622 $offsetParent
= $( $offsetParent
[ 0 ].ownerDocument
.body
);
4624 isBody
= $offsetParent
.is( 'body' );
4625 scrollableX
= $offsetParent
.css( 'overflow-x' ) === 'scroll' || $offsetParent
.css( 'overflow-x' ) === 'auto';
4626 scrollableY
= $offsetParent
.css( 'overflow-y' ) === 'scroll' || $offsetParent
.css( 'overflow-y' ) === 'auto';
4628 vertScrollbarWidth
= $offsetParent
.innerWidth() - $offsetParent
.prop( 'clientWidth' );
4629 horizScrollbarHeight
= $offsetParent
.innerHeight() - $offsetParent
.prop( 'clientHeight' );
4630 // We don't need to compute and add scrollTop and scrollLeft if the scrollable container is the body,
4631 // or if it isn't scrollable
4632 scrollTop
= scrollableY
&& !isBody
? $offsetParent
.scrollTop() : 0;
4633 scrollLeft
= scrollableX
&& !isBody
? OO
.ui
.Element
.static.getScrollLeft( $offsetParent
[ 0 ] ) : 0;
4635 // Avoid passing the <body> to getRelativePosition(), because it won't return what we expect
4636 // if the <body> has a margin
4637 containerPos
= isBody
?
4638 this.$floatableContainer
.offset() :
4639 OO
.ui
.Element
.static.getRelativePosition( this.$floatableContainer
, $offsetParent
);
4640 containerPos
.bottom
= containerPos
.top
+ this.$floatableContainer
.outerHeight();
4641 containerPos
.right
= containerPos
.left
+ this.$floatableContainer
.outerWidth();
4642 containerPos
.start
= direction
=== 'rtl' ? containerPos
.right
: containerPos
.left
;
4643 containerPos
.end
= direction
=== 'rtl' ? containerPos
.left
: containerPos
.right
;
4645 if ( this.verticalPosition
=== 'below' ) {
4646 newPos
.top
= containerPos
.bottom
;
4647 } else if ( this.verticalPosition
=== 'above' ) {
4648 newPos
.bottom
= $offsetParent
.outerHeight() - containerPos
.top
;
4649 } else if ( this.verticalPosition
=== 'top' ) {
4650 newPos
.top
= containerPos
.top
;
4651 } else if ( this.verticalPosition
=== 'bottom' ) {
4652 newPos
.bottom
= $offsetParent
.outerHeight() - containerPos
.bottom
;
4653 } else if ( this.verticalPosition
=== 'center' ) {
4654 newPos
.top
= containerPos
.top
+
4655 ( this.$floatableContainer
.height() - this.$floatable
.height() ) / 2;
4658 if ( this.horizontalPosition
=== 'before' ) {
4659 newPos
.end
= containerPos
.start
;
4660 } else if ( this.horizontalPosition
=== 'after' ) {
4661 newPos
.start
= containerPos
.end
;
4662 } else if ( this.horizontalPosition
=== 'start' ) {
4663 newPos
.start
= containerPos
.start
;
4664 } else if ( this.horizontalPosition
=== 'end' ) {
4665 newPos
.end
= containerPos
.end
;
4666 } else if ( this.horizontalPosition
=== 'center' ) {
4667 newPos
.left
= containerPos
.left
+
4668 ( this.$floatableContainer
.width() - this.$floatable
.width() ) / 2;
4671 if ( newPos
.start
!== undefined ) {
4672 if ( direction
=== 'rtl' ) {
4673 newPos
.right
= ( isBody
? $( $offsetParent
[ 0 ].ownerDocument
.documentElement
) : $offsetParent
).outerWidth() - newPos
.start
;
4675 newPos
.left
= newPos
.start
;
4677 delete newPos
.start
;
4679 if ( newPos
.end
!== undefined ) {
4680 if ( direction
=== 'rtl' ) {
4681 newPos
.left
= newPos
.end
;
4683 newPos
.right
= ( isBody
? $( $offsetParent
[ 0 ].ownerDocument
.documentElement
) : $offsetParent
).outerWidth() - newPos
.end
;
4688 // Account for scroll position
4689 if ( newPos
.top
!== '' ) {
4690 newPos
.top
+= scrollTop
;
4692 if ( newPos
.bottom
!== '' ) {
4693 newPos
.bottom
-= scrollTop
;
4695 if ( newPos
.left
!== '' ) {
4696 newPos
.left
+= scrollLeft
;
4698 if ( newPos
.right
!== '' ) {
4699 newPos
.right
-= scrollLeft
;
4702 // Account for scrollbar gutter
4703 if ( newPos
.bottom
!== '' ) {
4704 newPos
.bottom
-= horizScrollbarHeight
;
4706 if ( direction
=== 'rtl' ) {
4707 if ( newPos
.left
!== '' ) {
4708 newPos
.left
-= vertScrollbarWidth
;
4711 if ( newPos
.right
!== '' ) {
4712 newPos
.right
-= vertScrollbarWidth
;
4720 * Element that can be automatically clipped to visible boundaries.
4722 * Whenever the element's natural height changes, you have to call
4723 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
4724 * clipping correctly.
4726 * The dimensions of #$clippableContainer will be compared to the boundaries of the
4727 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
4728 * then #$clippable will be given a fixed reduced height and/or width and will be made
4729 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
4730 * but you can build a static footer by setting #$clippableContainer to an element that contains
4731 * #$clippable and the footer.
4737 * @param {Object} [config] Configuration options
4738 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
4739 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
4740 * omit to use #$clippable
4742 OO
.ui
.mixin
.ClippableElement
= function OoUiMixinClippableElement( config
) {
4743 // Configuration initialization
4744 config
= config
|| {};
4747 this.$clippable
= null;
4748 this.$clippableContainer
= null;
4749 this.clipping
= false;
4750 this.clippedHorizontally
= false;
4751 this.clippedVertically
= false;
4752 this.$clippableScrollableContainer
= null;
4753 this.$clippableScroller
= null;
4754 this.$clippableWindow
= null;
4755 this.idealWidth
= null;
4756 this.idealHeight
= null;
4757 this.onClippableScrollHandler
= this.clip
.bind( this );
4758 this.onClippableWindowResizeHandler
= this.clip
.bind( this );
4761 if ( config
.$clippableContainer
) {
4762 this.setClippableContainer( config
.$clippableContainer
);
4764 this.setClippableElement( config
.$clippable
|| this.$element
);
4770 * Set clippable element.
4772 * If an element is already set, it will be cleaned up before setting up the new element.
4774 * @param {jQuery} $clippable Element to make clippable
4776 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableElement = function ( $clippable
) {
4777 if ( this.$clippable
) {
4778 this.$clippable
.removeClass( 'oo-ui-clippableElement-clippable' );
4779 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
4780 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4783 this.$clippable
= $clippable
.addClass( 'oo-ui-clippableElement-clippable' );
4788 * Set clippable container.
4790 * This is the container that will be measured when deciding whether to clip. When clipping,
4791 * #$clippable will be resized in order to keep the clippable container fully visible.
4793 * If the clippable container is unset, #$clippable will be used.
4795 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
4797 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableContainer = function ( $clippableContainer
) {
4798 this.$clippableContainer
= $clippableContainer
;
4799 if ( this.$clippable
) {
4807 * Do not turn clipping on until after the element is attached to the DOM and visible.
4809 * @param {boolean} [clipping] Enable clipping, omit to toggle
4812 OO
.ui
.mixin
.ClippableElement
.prototype.toggleClipping = function ( clipping
) {
4813 clipping
= clipping
=== undefined ? !this.clipping
: !!clipping
;
4815 if ( clipping
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
4816 OO
.ui
.warnDeprecation( 'ClippableElement#toggleClipping: Before calling this method, the element must be attached to the DOM.' );
4817 this.warnedUnattached
= true;
4820 if ( this.clipping
!== clipping
) {
4821 this.clipping
= clipping
;
4823 this.$clippableScrollableContainer
= $( this.getClosestScrollableElementContainer() );
4824 // If the clippable container is the root, we have to listen to scroll events and check
4825 // jQuery.scrollTop on the window because of browser inconsistencies
4826 this.$clippableScroller
= this.$clippableScrollableContainer
.is( 'html, body' ) ?
4827 $( OO
.ui
.Element
.static.getWindow( this.$clippableScrollableContainer
) ) :
4828 this.$clippableScrollableContainer
;
4829 this.$clippableScroller
.on( 'scroll', this.onClippableScrollHandler
);
4830 this.$clippableWindow
= $( this.getElementWindow() )
4831 .on( 'resize', this.onClippableWindowResizeHandler
);
4832 // Initial clip after visible
4835 this.$clippable
.css( {
4843 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4845 this.$clippableScrollableContainer
= null;
4846 this.$clippableScroller
.off( 'scroll', this.onClippableScrollHandler
);
4847 this.$clippableScroller
= null;
4848 this.$clippableWindow
.off( 'resize', this.onClippableWindowResizeHandler
);
4849 this.$clippableWindow
= null;
4857 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
4859 * @return {boolean} Element will be clipped to the visible area
4861 OO
.ui
.mixin
.ClippableElement
.prototype.isClipping = function () {
4862 return this.clipping
;
4866 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
4868 * @return {boolean} Part of the element is being clipped
4870 OO
.ui
.mixin
.ClippableElement
.prototype.isClipped = function () {
4871 return this.clippedHorizontally
|| this.clippedVertically
;
4875 * Check if the right of the element is being clipped by the nearest scrollable container.
4877 * @return {boolean} Part of the element is being clipped
4879 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedHorizontally = function () {
4880 return this.clippedHorizontally
;
4884 * Check if the bottom of the element is being clipped by the nearest scrollable container.
4886 * @return {boolean} Part of the element is being clipped
4888 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedVertically = function () {
4889 return this.clippedVertically
;
4893 * Set the ideal size. These are the dimensions #$clippable will have when it's not being clipped.
4895 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
4896 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
4898 OO
.ui
.mixin
.ClippableElement
.prototype.setIdealSize = function ( width
, height
) {
4899 this.idealWidth
= width
;
4900 this.idealHeight
= height
;
4902 if ( !this.clipping
) {
4903 // Update dimensions
4904 this.$clippable
.css( { width
: width
, height
: height
} );
4906 // While clipping, idealWidth and idealHeight are not considered
4910 * Return the side of the clippable on which it is "anchored" (aligned to something else).
4911 * ClippableElement will clip the opposite side when reducing element's width.
4913 * Classes that mix in ClippableElement should override this to return 'right' if their
4914 * clippable is absolutely positioned and using 'right: Npx' (and not using 'left').
4915 * If your class also mixes in FloatableElement, this is handled automatically.
4917 * (This can't be guessed from the actual CSS because the computed values for 'left'/'right' are
4918 * always in pixels, even if they were unset or set to 'auto'.)
4920 * When in doubt, 'left' (or 'right' in RTL) is a sane fallback.
4922 * @return {string} 'left' or 'right'
4924 OO
.ui
.mixin
.ClippableElement
.prototype.getHorizontalAnchorEdge = function () {
4925 if ( this.computePosition
&& this.positioning
&& this.computePosition().right
!== '' ) {
4932 * Return the side of the clippable on which it is "anchored" (aligned to something else).
4933 * ClippableElement will clip the opposite side when reducing element's width.
4935 * Classes that mix in ClippableElement should override this to return 'bottom' if their
4936 * clippable is absolutely positioned and using 'bottom: Npx' (and not using 'top').
4937 * If your class also mixes in FloatableElement, this is handled automatically.
4939 * (This can't be guessed from the actual CSS because the computed values for 'left'/'right' are
4940 * always in pixels, even if they were unset or set to 'auto'.)
4942 * When in doubt, 'top' is a sane fallback.
4944 * @return {string} 'top' or 'bottom'
4946 OO
.ui
.mixin
.ClippableElement
.prototype.getVerticalAnchorEdge = function () {
4947 if ( this.computePosition
&& this.positioning
&& this.computePosition().bottom
!== '' ) {
4954 * Clip element to visible boundaries and allow scrolling when needed. You should call this method
4955 * when the element's natural height changes.
4957 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
4958 * overlapped by, the visible area of the nearest scrollable container.
4960 * Because calling clip() when the natural height changes isn't always possible, we also set
4961 * max-height when the element isn't being clipped. This means that if the element tries to grow
4962 * beyond the edge, something reasonable will happen before clip() is called.
4966 OO
.ui
.mixin
.ClippableElement
.prototype.clip = function () {
4967 var extraHeight
, extraWidth
, viewportSpacing
,
4968 desiredWidth
, desiredHeight
, allotedWidth
, allotedHeight
,
4969 naturalWidth
, naturalHeight
, clipWidth
, clipHeight
,
4970 $item
, itemRect
, $viewport
, viewportRect
, availableRect
,
4971 direction
, vertScrollbarWidth
, horizScrollbarHeight
,
4972 // Extra tolerance so that the sloppy code below doesn't result in results that are off
4973 // by one or two pixels. (And also so that we have space to display drop shadows.)
4974 // Chosen by fair dice roll.
4977 if ( !this.clipping
) {
4978 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
4982 function rectIntersection( a
, b
) {
4984 out
.top
= Math
.max( a
.top
, b
.top
);
4985 out
.left
= Math
.max( a
.left
, b
.left
);
4986 out
.bottom
= Math
.min( a
.bottom
, b
.bottom
);
4987 out
.right
= Math
.min( a
.right
, b
.right
);
4991 viewportSpacing
= OO
.ui
.getViewportSpacing();
4993 if ( this.$clippableScrollableContainer
.is( 'html, body' ) ) {
4994 $viewport
= $( this.$clippableScrollableContainer
[ 0 ].ownerDocument
.body
);
4995 // Dimensions of the browser window, rather than the element!
4999 right
: document
.documentElement
.clientWidth
,
5000 bottom
: document
.documentElement
.clientHeight
5002 viewportRect
.top
+= viewportSpacing
.top
;
5003 viewportRect
.left
+= viewportSpacing
.left
;
5004 viewportRect
.right
-= viewportSpacing
.right
;
5005 viewportRect
.bottom
-= viewportSpacing
.bottom
;
5007 $viewport
= this.$clippableScrollableContainer
;
5008 viewportRect
= $viewport
[ 0 ].getBoundingClientRect();
5009 // Convert into a plain object
5010 viewportRect
= $.extend( {}, viewportRect
);
5013 // Account for scrollbar gutter
5014 direction
= $viewport
.css( 'direction' );
5015 vertScrollbarWidth
= $viewport
.innerWidth() - $viewport
.prop( 'clientWidth' );
5016 horizScrollbarHeight
= $viewport
.innerHeight() - $viewport
.prop( 'clientHeight' );
5017 viewportRect
.bottom
-= horizScrollbarHeight
;
5018 if ( direction
=== 'rtl' ) {
5019 viewportRect
.left
+= vertScrollbarWidth
;
5021 viewportRect
.right
-= vertScrollbarWidth
;
5024 // Add arbitrary tolerance
5025 viewportRect
.top
+= buffer
;
5026 viewportRect
.left
+= buffer
;
5027 viewportRect
.right
-= buffer
;
5028 viewportRect
.bottom
-= buffer
;
5030 $item
= this.$clippableContainer
|| this.$clippable
;
5032 extraHeight
= $item
.outerHeight() - this.$clippable
.outerHeight();
5033 extraWidth
= $item
.outerWidth() - this.$clippable
.outerWidth();
5035 itemRect
= $item
[ 0 ].getBoundingClientRect();
5036 // Convert into a plain object
5037 itemRect
= $.extend( {}, itemRect
);
5039 // Item might already be clipped, so we can't just use its dimensions (in case we might need to
5040 // make it larger than before). Extend the rectangle to the maximum size we are allowed to take.
5041 if ( this.getHorizontalAnchorEdge() === 'right' ) {
5042 itemRect
.left
= viewportRect
.left
;
5044 itemRect
.right
= viewportRect
.right
;
5046 if ( this.getVerticalAnchorEdge() === 'bottom' ) {
5047 itemRect
.top
= viewportRect
.top
;
5049 itemRect
.bottom
= viewportRect
.bottom
;
5052 availableRect
= rectIntersection( viewportRect
, itemRect
);
5054 desiredWidth
= Math
.max( 0, availableRect
.right
- availableRect
.left
);
5055 desiredHeight
= Math
.max( 0, availableRect
.bottom
- availableRect
.top
);
5056 // It should never be desirable to exceed the dimensions of the browser viewport... right?
5057 desiredWidth
= Math
.min( desiredWidth
,
5058 document
.documentElement
.clientWidth
- viewportSpacing
.left
- viewportSpacing
.right
);
5059 desiredHeight
= Math
.min( desiredHeight
,
5060 document
.documentElement
.clientHeight
- viewportSpacing
.top
- viewportSpacing
.right
);
5061 allotedWidth
= Math
.ceil( desiredWidth
- extraWidth
);
5062 allotedHeight
= Math
.ceil( desiredHeight
- extraHeight
);
5063 naturalWidth
= this.$clippable
.prop( 'scrollWidth' );
5064 naturalHeight
= this.$clippable
.prop( 'scrollHeight' );
5065 clipWidth
= allotedWidth
< naturalWidth
;
5066 clipHeight
= allotedHeight
< naturalHeight
;
5069 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. See T157672.
5070 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case.
5071 this.$clippable
.css( 'overflowX', 'scroll' );
5072 void this.$clippable
[ 0 ].offsetHeight
; // Force reflow
5073 this.$clippable
.css( {
5074 width
: Math
.max( 0, allotedWidth
),
5078 this.$clippable
.css( {
5080 width
: this.idealWidth
|| '',
5081 maxWidth
: Math
.max( 0, allotedWidth
)
5085 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. See T157672.
5086 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case.
5087 this.$clippable
.css( 'overflowY', 'scroll' );
5088 void this.$clippable
[ 0 ].offsetHeight
; // Force reflow
5089 this.$clippable
.css( {
5090 height
: Math
.max( 0, allotedHeight
),
5094 this.$clippable
.css( {
5096 height
: this.idealHeight
|| '',
5097 maxHeight
: Math
.max( 0, allotedHeight
)
5101 // If we stopped clipping in at least one of the dimensions
5102 if ( ( this.clippedHorizontally
&& !clipWidth
) || ( this.clippedVertically
&& !clipHeight
) ) {
5103 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
5106 this.clippedHorizontally
= clipWidth
;
5107 this.clippedVertically
= clipHeight
;
5113 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
5114 * By default, each popup has an anchor that points toward its origin.
5115 * Please see the [OOUI documentation on MediaWiki.org] [1] for more information and examples.
5117 * Unlike most widgets, PopupWidget is initially hidden and must be shown by calling #toggle.
5120 * // A popup widget.
5121 * var popup = new OO.ui.PopupWidget( {
5122 * $content: $( '<p>Hi there!</p>' ),
5127 * $( 'body' ).append( popup.$element );
5128 * // To display the popup, toggle the visibility to 'true'.
5129 * popup.toggle( true );
5131 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups
5134 * @extends OO.ui.Widget
5135 * @mixins OO.ui.mixin.LabelElement
5136 * @mixins OO.ui.mixin.ClippableElement
5137 * @mixins OO.ui.mixin.FloatableElement
5140 * @param {Object} [config] Configuration options
5141 * @cfg {number|null} [width=320] Width of popup in pixels. Pass `null` to use automatic width.
5142 * @cfg {number|null} [height=null] Height of popup in pixels. Pass `null` to use automatic height.
5143 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
5144 * @cfg {string} [position='below'] Where to position the popup relative to $floatableContainer
5145 * 'above': Put popup above $floatableContainer; anchor points down to the horizontal center
5146 * of $floatableContainer
5147 * 'below': Put popup below $floatableContainer; anchor points up to the horizontal center
5148 * of $floatableContainer
5149 * 'before': Put popup to the left (LTR) / right (RTL) of $floatableContainer; anchor points
5150 * endwards (right/left) to the vertical center of $floatableContainer
5151 * 'after': Put popup to the right (LTR) / left (RTL) of $floatableContainer; anchor points
5152 * startwards (left/right) to the vertical center of $floatableContainer
5153 * @cfg {string} [align='center'] How to align the popup to $floatableContainer
5154 * 'forwards': If position is above/below, move the popup as far endwards (right in LTR, left in RTL)
5155 * as possible while still keeping the anchor within the popup;
5156 * if position is before/after, move the popup as far downwards as possible.
5157 * 'backwards': If position is above/below, move the popup as far startwards (left in LTR, right in RTL)
5158 * as possible while still keeping the anchor within the popup;
5159 * if position in before/after, move the popup as far upwards as possible.
5160 * 'center': Horizontally (if position is above/below) or vertically (before/after) align the center
5161 * of the popup with the center of $floatableContainer.
5162 * 'force-left': Alias for 'forwards' in LTR and 'backwards' in RTL
5163 * 'force-right': Alias for 'backwards' in RTL and 'forwards' in LTR
5164 * @cfg {boolean} [autoFlip=true] Whether to automatically switch the popup's position between
5165 * 'above' and 'below', or between 'before' and 'after', if there is not enough space in the
5166 * desired direction to display the popup without clipping
5167 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
5168 * See the [OOUI docs on MediaWiki][3] for an example.
5169 * [3]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups#containerExample
5170 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
5171 * @cfg {jQuery} [$content] Content to append to the popup's body
5172 * @cfg {jQuery} [$footer] Content to append to the popup's footer
5173 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
5174 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
5175 * This config option is only relevant if #autoClose is set to `true`. See the [OOUI documentation on MediaWiki][2]
5177 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups#autocloseExample
5178 * @cfg {boolean} [head=false] Show a popup header that contains a #label (if specified) and close
5180 * @cfg {boolean} [padded=false] Add padding to the popup's body
5182 OO
.ui
.PopupWidget
= function OoUiPopupWidget( config
) {
5183 // Configuration initialization
5184 config
= config
|| {};
5186 // Parent constructor
5187 OO
.ui
.PopupWidget
.parent
.call( this, config
);
5189 // Properties (must be set before ClippableElement constructor call)
5190 this.$body
= $( '<div>' );
5191 this.$popup
= $( '<div>' );
5193 // Mixin constructors
5194 OO
.ui
.mixin
.LabelElement
.call( this, config
);
5195 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, {
5196 $clippable
: this.$body
,
5197 $clippableContainer
: this.$popup
5199 OO
.ui
.mixin
.FloatableElement
.call( this, config
);
5202 this.$anchor
= $( '<div>' );
5203 // If undefined, will be computed lazily in computePosition()
5204 this.$container
= config
.$container
;
5205 this.containerPadding
= config
.containerPadding
!== undefined ? config
.containerPadding
: 10;
5206 this.autoClose
= !!config
.autoClose
;
5207 this.transitionTimeout
= null;
5208 this.anchored
= false;
5209 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
5210 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
5213 this.setSize( config
.width
, config
.height
);
5214 this.toggleAnchor( config
.anchor
=== undefined || config
.anchor
);
5215 this.setAlignment( config
.align
|| 'center' );
5216 this.setPosition( config
.position
|| 'below' );
5217 this.setAutoFlip( config
.autoFlip
=== undefined || config
.autoFlip
);
5218 this.setAutoCloseIgnore( config
.$autoCloseIgnore
);
5219 this.$body
.addClass( 'oo-ui-popupWidget-body' );
5220 this.$anchor
.addClass( 'oo-ui-popupWidget-anchor' );
5222 .addClass( 'oo-ui-popupWidget-popup' )
5223 .append( this.$body
);
5225 .addClass( 'oo-ui-popupWidget' )
5226 .append( this.$popup
, this.$anchor
);
5227 // Move content, which was added to #$element by OO.ui.Widget, to the body
5228 // FIXME This is gross, we should use '$body' or something for the config
5229 if ( config
.$content
instanceof jQuery
) {
5230 this.$body
.append( config
.$content
);
5233 if ( config
.padded
) {
5234 this.$body
.addClass( 'oo-ui-popupWidget-body-padded' );
5237 if ( config
.head
) {
5238 this.closeButton
= new OO
.ui
.ButtonWidget( { framed
: false, icon
: 'close' } );
5239 this.closeButton
.connect( this, { click
: 'onCloseButtonClick' } );
5240 this.$head
= $( '<div>' )
5241 .addClass( 'oo-ui-popupWidget-head' )
5242 .append( this.$label
, this.closeButton
.$element
);
5243 this.$popup
.prepend( this.$head
);
5246 if ( config
.$footer
) {
5247 this.$footer
= $( '<div>' )
5248 .addClass( 'oo-ui-popupWidget-footer' )
5249 .append( config
.$footer
);
5250 this.$popup
.append( this.$footer
);
5253 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
5254 // that reference properties not initialized at that time of parent class construction
5255 // TODO: Find a better way to handle post-constructor setup
5256 this.visible
= false;
5257 this.$element
.addClass( 'oo-ui-element-hidden' );
5262 OO
.inheritClass( OO
.ui
.PopupWidget
, OO
.ui
.Widget
);
5263 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.LabelElement
);
5264 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.ClippableElement
);
5265 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.FloatableElement
);
5272 * The popup is ready: it is visible and has been positioned and clipped.
5278 * Handles document mouse down events.
5281 * @param {MouseEvent} e Mouse down event
5283 OO
.ui
.PopupWidget
.prototype.onDocumentMouseDown = function ( e
) {
5286 !OO
.ui
.contains( this.$element
.add( this.$autoCloseIgnore
).get(), e
.target
, true )
5288 this.toggle( false );
5292 // Deprecated alias since 0.28.3
5293 OO
.ui
.PopupWidget
.prototype.onMouseDown = function () {
5294 OO
.ui
.warnDeprecation( 'onMouseDown is deprecated, use onDocumentMouseDown instead' );
5295 this.onDocumentMouseDown
.apply( this, arguments
);
5299 * Bind document mouse down listener.
5303 OO
.ui
.PopupWidget
.prototype.bindDocumentMouseDownListener = function () {
5304 // Capture clicks outside popup
5305 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
5306 // We add 'click' event because iOS safari needs to respond to this event.
5307 // We can't use 'touchstart' (as is usually the equivalent to 'mousedown') because
5308 // then it will trigger when scrolling. While iOS Safari has some reported behavior
5309 // of occasionally not emitting 'click' properly, that event seems to be the standard
5310 // that it should be emitting, so we add it to this and will operate the event handler
5311 // on whichever of these events was triggered first
5312 this.getElementDocument().addEventListener( 'click', this.onDocumentMouseDownHandler
, true );
5315 // Deprecated alias since 0.28.3
5316 OO
.ui
.PopupWidget
.prototype.bindMouseDownListener = function () {
5317 OO
.ui
.warnDeprecation( 'bindMouseDownListener is deprecated, use bindDocumentMouseDownListener instead' );
5318 this.bindDocumentMouseDownListener
.apply( this, arguments
);
5322 * Handles close button click events.
5326 OO
.ui
.PopupWidget
.prototype.onCloseButtonClick = function () {
5327 if ( this.isVisible() ) {
5328 this.toggle( false );
5333 * Unbind document mouse down listener.
5337 OO
.ui
.PopupWidget
.prototype.unbindDocumentMouseDownListener = function () {
5338 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
5339 this.getElementDocument().removeEventListener( 'click', this.onDocumentMouseDownHandler
, true );
5342 // Deprecated alias since 0.28.3
5343 OO
.ui
.PopupWidget
.prototype.unbindMouseDownListener = function () {
5344 OO
.ui
.warnDeprecation( 'unbindMouseDownListener is deprecated, use unbindDocumentMouseDownListener instead' );
5345 this.unbindDocumentMouseDownListener
.apply( this, arguments
);
5349 * Handles document key down events.
5352 * @param {KeyboardEvent} e Key down event
5354 OO
.ui
.PopupWidget
.prototype.onDocumentKeyDown = function ( e
) {
5356 e
.which
=== OO
.ui
.Keys
.ESCAPE
&&
5359 this.toggle( false );
5361 e
.stopPropagation();
5366 * Bind document key down listener.
5370 OO
.ui
.PopupWidget
.prototype.bindDocumentKeyDownListener = function () {
5371 this.getElementDocument().addEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
5374 // Deprecated alias since 0.28.3
5375 OO
.ui
.PopupWidget
.prototype.bindKeyDownListener = function () {
5376 OO
.ui
.warnDeprecation( 'bindKeyDownListener is deprecated, use bindDocumentKeyDownListener instead' );
5377 this.bindDocumentKeyDownListener
.apply( this, arguments
);
5381 * Unbind document key down listener.
5385 OO
.ui
.PopupWidget
.prototype.unbindDocumentKeyDownListener = function () {
5386 this.getElementDocument().removeEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
5389 // Deprecated alias since 0.28.3
5390 OO
.ui
.PopupWidget
.prototype.unbindKeyDownListener = function () {
5391 OO
.ui
.warnDeprecation( 'unbindKeyDownListener is deprecated, use unbindDocumentKeyDownListener instead' );
5392 this.unbindDocumentKeyDownListener
.apply( this, arguments
);
5396 * Show, hide, or toggle the visibility of the anchor.
5398 * @param {boolean} [show] Show anchor, omit to toggle
5400 OO
.ui
.PopupWidget
.prototype.toggleAnchor = function ( show
) {
5401 show
= show
=== undefined ? !this.anchored
: !!show
;
5403 if ( this.anchored
!== show
) {
5405 this.$element
.addClass( 'oo-ui-popupWidget-anchored' );
5406 this.$element
.addClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge
);
5408 this.$element
.removeClass( 'oo-ui-popupWidget-anchored' );
5409 this.$element
.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge
);
5411 this.anchored
= show
;
5416 * Change which edge the anchor appears on.
5418 * @param {string} edge 'top', 'bottom', 'start' or 'end'
5420 OO
.ui
.PopupWidget
.prototype.setAnchorEdge = function ( edge
) {
5421 if ( [ 'top', 'bottom', 'start', 'end' ].indexOf( edge
) === -1 ) {
5422 throw new Error( 'Invalid value for edge: ' + edge
);
5424 if ( this.anchorEdge
!== null ) {
5425 this.$element
.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge
);
5427 this.anchorEdge
= edge
;
5428 if ( this.anchored
) {
5429 this.$element
.addClass( 'oo-ui-popupWidget-anchored-' + edge
);
5434 * Check if the anchor is visible.
5436 * @return {boolean} Anchor is visible
5438 OO
.ui
.PopupWidget
.prototype.hasAnchor = function () {
5439 return this.anchored
;
5443 * Toggle visibility of the popup. The popup is initially hidden and must be shown by calling
5444 * `.toggle( true )` after its #$element is attached to the DOM.
5446 * Do not show the popup while it is not attached to the DOM. The calculations required to display
5447 * it in the right place and with the right dimensions only work correctly while it is attached.
5448 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
5449 * strictly enforced, so currently it only generates a warning in the browser console.
5454 OO
.ui
.PopupWidget
.prototype.toggle = function ( show
) {
5455 var change
, normalHeight
, oppositeHeight
, normalWidth
, oppositeWidth
;
5456 show
= show
=== undefined ? !this.isVisible() : !!show
;
5458 change
= show
!== this.isVisible();
5460 if ( show
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
5461 OO
.ui
.warnDeprecation( 'PopupWidget#toggle: Before calling this method, the popup must be attached to the DOM.' );
5462 this.warnedUnattached
= true;
5464 if ( show
&& !this.$floatableContainer
&& this.isElementAttached() ) {
5465 // Fall back to the parent node if the floatableContainer is not set
5466 this.setFloatableContainer( this.$element
.parent() );
5469 if ( change
&& show
&& this.autoFlip
) {
5470 // Reset auto-flipping before showing the popup again. It's possible we no longer need to flip
5471 // (e.g. if the user scrolled).
5472 this.isAutoFlipped
= false;
5476 OO
.ui
.PopupWidget
.parent
.prototype.toggle
.call( this, show
);
5479 this.togglePositioning( show
&& !!this.$floatableContainer
);
5482 if ( this.autoClose
) {
5483 this.bindDocumentMouseDownListener();
5484 this.bindDocumentKeyDownListener();
5486 this.updateDimensions();
5487 this.toggleClipping( true );
5489 if ( this.autoFlip
) {
5490 if ( this.popupPosition
=== 'above' || this.popupPosition
=== 'below' ) {
5491 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
5492 // If opening the popup in the normal direction causes it to be clipped, open
5493 // in the opposite one instead
5494 normalHeight
= this.$element
.height();
5495 this.isAutoFlipped
= !this.isAutoFlipped
;
5497 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
5498 // If that also causes it to be clipped, open in whichever direction
5499 // we have more space
5500 oppositeHeight
= this.$element
.height();
5501 if ( oppositeHeight
< normalHeight
) {
5502 this.isAutoFlipped
= !this.isAutoFlipped
;
5508 if ( this.popupPosition
=== 'before' || this.popupPosition
=== 'after' ) {
5509 if ( this.isClippedHorizontally() || this.isFloatableOutOfView() ) {
5510 // If opening the popup in the normal direction causes it to be clipped, open
5511 // in the opposite one instead
5512 normalWidth
= this.$element
.width();
5513 this.isAutoFlipped
= !this.isAutoFlipped
;
5514 // Due to T180173 horizontally clipped PopupWidgets have messed up dimensions,
5515 // which causes positioning to be off. Toggle clipping back and fort to work around.
5516 this.toggleClipping( false );
5518 this.toggleClipping( true );
5519 if ( this.isClippedHorizontally() || this.isFloatableOutOfView() ) {
5520 // If that also causes it to be clipped, open in whichever direction
5521 // we have more space
5522 oppositeWidth
= this.$element
.width();
5523 if ( oppositeWidth
< normalWidth
) {
5524 this.isAutoFlipped
= !this.isAutoFlipped
;
5525 // Due to T180173 horizontally clipped PopupWidgets have messed up dimensions,
5526 // which causes positioning to be off. Toggle clipping back and fort to work around.
5527 this.toggleClipping( false );
5529 this.toggleClipping( true );
5536 this.emit( 'ready' );
5538 this.toggleClipping( false );
5539 if ( this.autoClose
) {
5540 this.unbindDocumentMouseDownListener();
5541 this.unbindDocumentKeyDownListener();
5550 * Set the size of the popup.
5552 * Changing the size may also change the popup's position depending on the alignment.
5554 * @param {number|null} [width=320] Width in pixels. Pass `null` to use automatic width.
5555 * @param {number|null} [height=null] Height in pixels. Pass `null` to use automatic height.
5556 * @param {boolean} [transition=false] Use a smooth transition
5559 OO
.ui
.PopupWidget
.prototype.setSize = function ( width
, height
, transition
) {
5560 this.width
= width
!== undefined ? width
: 320;
5561 this.height
= height
!== undefined ? height
: null;
5562 if ( this.isVisible() ) {
5563 this.updateDimensions( transition
);
5568 * Update the size and position.
5570 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
5571 * be called automatically.
5573 * @param {boolean} [transition=false] Use a smooth transition
5576 OO
.ui
.PopupWidget
.prototype.updateDimensions = function ( transition
) {
5579 // Prevent transition from being interrupted
5580 clearTimeout( this.transitionTimeout
);
5582 // Enable transition
5583 this.$element
.addClass( 'oo-ui-popupWidget-transitioning' );
5589 // Prevent transitioning after transition is complete
5590 this.transitionTimeout
= setTimeout( function () {
5591 widget
.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
5594 // Prevent transitioning immediately
5595 this.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
5602 OO
.ui
.PopupWidget
.prototype.computePosition = function () {
5603 var direction
, align
, vertical
, start
, end
, near
, far
, sizeProp
, popupSize
, anchorSize
, anchorPos
,
5604 anchorOffset
, anchorMargin
, parentPosition
, positionProp
, positionAdjustment
, floatablePos
,
5605 offsetParentPos
, containerPos
, popupPosition
, viewportSpacing
,
5607 anchorCss
= { left
: '', right
: '', top
: '', bottom
: '' },
5608 popupPositionOppositeMap
= {
5616 'force-left': 'backwards',
5617 'force-right': 'forwards'
5620 'force-left': 'forwards',
5621 'force-right': 'backwards'
5633 backwards
: this.anchored
? 'before' : 'end'
5641 if ( !this.$container
) {
5642 // Lazy-initialize $container if not specified in constructor
5643 this.$container
= $( this.getClosestScrollableElementContainer() );
5645 direction
= this.$container
.css( 'direction' );
5647 // Set height and width before we do anything else, since it might cause our measurements
5648 // to change (e.g. due to scrollbars appearing or disappearing), and it also affects centering
5650 width
: this.width
!== null ? this.width
: 'auto',
5651 height
: this.height
!== null ? this.height
: 'auto'
5654 align
= alignMap
[ direction
][ this.align
] || this.align
;
5655 popupPosition
= this.popupPosition
;
5656 if ( this.isAutoFlipped
) {
5657 popupPosition
= popupPositionOppositeMap
[ popupPosition
];
5660 // If the popup is positioned before or after, then the anchor positioning is vertical, otherwise horizontal
5661 vertical
= popupPosition
=== 'before' || popupPosition
=== 'after';
5662 start
= vertical
? 'top' : ( direction
=== 'rtl' ? 'right' : 'left' );
5663 end
= vertical
? 'bottom' : ( direction
=== 'rtl' ? 'left' : 'right' );
5664 near
= vertical
? 'top' : 'left';
5665 far
= vertical
? 'bottom' : 'right';
5666 sizeProp
= vertical
? 'Height' : 'Width';
5667 popupSize
= vertical
? ( this.height
|| this.$popup
.height() ) : ( this.width
|| this.$popup
.width() );
5669 this.setAnchorEdge( anchorEdgeMap
[ popupPosition
] );
5670 this.horizontalPosition
= vertical
? popupPosition
: hPosMap
[ align
];
5671 this.verticalPosition
= vertical
? vPosMap
[ align
] : popupPosition
;
5674 parentPosition
= OO
.ui
.mixin
.FloatableElement
.prototype.computePosition
.call( this );
5675 // Find out which property FloatableElement used for positioning, and adjust that value
5676 positionProp
= vertical
?
5677 ( parentPosition
.top
!== '' ? 'top' : 'bottom' ) :
5678 ( parentPosition
.left
!== '' ? 'left' : 'right' );
5680 // Figure out where the near and far edges of the popup and $floatableContainer are
5681 floatablePos
= this.$floatableContainer
.offset();
5682 floatablePos
[ far
] = floatablePos
[ near
] + this.$floatableContainer
[ 'outer' + sizeProp
]();
5683 // Measure where the offsetParent is and compute our position based on that and parentPosition
5684 offsetParentPos
= this.$element
.offsetParent()[ 0 ] === document
.documentElement
?
5685 { top
: 0, left
: 0 } :
5686 this.$element
.offsetParent().offset();
5688 if ( positionProp
=== near
) {
5689 popupPos
[ near
] = offsetParentPos
[ near
] + parentPosition
[ near
];
5690 popupPos
[ far
] = popupPos
[ near
] + popupSize
;
5692 popupPos
[ far
] = offsetParentPos
[ near
] +
5693 this.$element
.offsetParent()[ 'inner' + sizeProp
]() - parentPosition
[ far
];
5694 popupPos
[ near
] = popupPos
[ far
] - popupSize
;
5697 if ( this.anchored
) {
5698 // Position the anchor (which is positioned relative to the popup) to point to $floatableContainer
5699 anchorPos
= ( floatablePos
[ start
] + floatablePos
[ end
] ) / 2;
5700 anchorOffset
= ( start
=== far
? -1 : 1 ) * ( anchorPos
- popupPos
[ start
] );
5702 // If the anchor is less than 2*anchorSize from either edge, move the popup to make more space
5703 // this.$anchor.width()/height() returns 0 because of the CSS trickery we use, so use scrollWidth/Height
5704 anchorSize
= this.$anchor
[ 0 ][ 'scroll' + sizeProp
];
5705 anchorMargin
= parseFloat( this.$anchor
.css( 'margin-' + start
) );
5706 if ( anchorOffset
+ anchorMargin
< 2 * anchorSize
) {
5707 // Not enough space for the anchor on the start side; pull the popup startwards
5708 positionAdjustment
= ( positionProp
=== start
? -1 : 1 ) *
5709 ( 2 * anchorSize
- ( anchorOffset
+ anchorMargin
) );
5710 } else if ( anchorOffset
+ anchorMargin
> popupSize
- 2 * anchorSize
) {
5711 // Not enough space for the anchor on the end side; pull the popup endwards
5712 positionAdjustment
= ( positionProp
=== end
? -1 : 1 ) *
5713 ( anchorOffset
+ anchorMargin
- ( popupSize
- 2 * anchorSize
) );
5715 positionAdjustment
= 0;
5718 positionAdjustment
= 0;
5721 // Check if the popup will go beyond the edge of this.$container
5722 containerPos
= this.$container
[ 0 ] === document
.documentElement
?
5723 { top
: 0, left
: 0 } :
5724 this.$container
.offset();
5725 containerPos
[ far
] = containerPos
[ near
] + this.$container
[ 'inner' + sizeProp
]();
5726 if ( this.$container
[ 0 ] === document
.documentElement
) {
5727 viewportSpacing
= OO
.ui
.getViewportSpacing();
5728 containerPos
[ near
] += viewportSpacing
[ near
];
5729 containerPos
[ far
] -= viewportSpacing
[ far
];
5731 // Take into account how much the popup will move because of the adjustments we're going to make
5732 popupPos
[ near
] += ( positionProp
=== near
? 1 : -1 ) * positionAdjustment
;
5733 popupPos
[ far
] += ( positionProp
=== near
? 1 : -1 ) * positionAdjustment
;
5734 if ( containerPos
[ near
] + this.containerPadding
> popupPos
[ near
] ) {
5735 // Popup goes beyond the near (left/top) edge, move it to the right/bottom
5736 positionAdjustment
+= ( positionProp
=== near
? 1 : -1 ) *
5737 ( containerPos
[ near
] + this.containerPadding
- popupPos
[ near
] );
5738 } else if ( containerPos
[ far
] - this.containerPadding
< popupPos
[ far
] ) {
5739 // Popup goes beyond the far (right/bottom) edge, move it to the left/top
5740 positionAdjustment
+= ( positionProp
=== far
? 1 : -1 ) *
5741 ( popupPos
[ far
] - ( containerPos
[ far
] - this.containerPadding
) );
5744 if ( this.anchored
) {
5745 // Adjust anchorOffset for positionAdjustment
5746 anchorOffset
+= ( positionProp
=== start
? -1 : 1 ) * positionAdjustment
;
5748 // Position the anchor
5749 anchorCss
[ start
] = anchorOffset
;
5750 this.$anchor
.css( anchorCss
);
5753 // Move the popup if needed
5754 parentPosition
[ positionProp
] += positionAdjustment
;
5756 return parentPosition
;
5760 * Set popup alignment
5762 * @param {string} [align=center] Alignment of the popup, `center`, `force-left`, `force-right`,
5763 * `backwards` or `forwards`.
5765 OO
.ui
.PopupWidget
.prototype.setAlignment = function ( align
) {
5766 // Validate alignment
5767 if ( [ 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align
) > -1 ) {
5770 this.align
= 'center';
5776 * Get popup alignment
5778 * @return {string} Alignment of the popup, `center`, `force-left`, `force-right`,
5779 * `backwards` or `forwards`.
5781 OO
.ui
.PopupWidget
.prototype.getAlignment = function () {
5786 * Change the positioning of the popup.
5788 * @param {string} position 'above', 'below', 'before' or 'after'
5790 OO
.ui
.PopupWidget
.prototype.setPosition = function ( position
) {
5791 if ( [ 'above', 'below', 'before', 'after' ].indexOf( position
) === -1 ) {
5794 this.popupPosition
= position
;
5799 * Get popup positioning.
5801 * @return {string} 'above', 'below', 'before' or 'after'
5803 OO
.ui
.PopupWidget
.prototype.getPosition = function () {
5804 return this.popupPosition
;
5808 * Set popup auto-flipping.
5810 * @param {boolean} autoFlip Whether to automatically switch the popup's position between
5811 * 'above' and 'below', or between 'before' and 'after', if there is not enough space in the
5812 * desired direction to display the popup without clipping
5814 OO
.ui
.PopupWidget
.prototype.setAutoFlip = function ( autoFlip
) {
5815 autoFlip
= !!autoFlip
;
5817 if ( this.autoFlip
!== autoFlip
) {
5818 this.autoFlip
= autoFlip
;
5823 * Set which elements will not close the popup when clicked.
5825 * For auto-closing popups, clicks on these elements will not cause the popup to auto-close.
5827 * @param {jQuery} $autoCloseIgnore Elements to ignore for auto-closing
5829 OO
.ui
.PopupWidget
.prototype.setAutoCloseIgnore = function ( $autoCloseIgnore
) {
5830 this.$autoCloseIgnore
= $autoCloseIgnore
;
5834 * Get an ID of the body element, this can be used as the
5835 * `aria-describedby` attribute for an input field.
5837 * @return {string} The ID of the body element
5839 OO
.ui
.PopupWidget
.prototype.getBodyId = function () {
5840 var id
= this.$body
.attr( 'id' );
5841 if ( id
=== undefined ) {
5842 id
= OO
.ui
.generateElementId();
5843 this.$body
.attr( 'id', id
);
5849 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
5850 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
5851 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
5852 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
5858 * @param {Object} [config] Configuration options
5859 * @cfg {Object} [popup] Configuration to pass to popup
5860 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
5862 OO
.ui
.mixin
.PopupElement
= function OoUiMixinPopupElement( config
) {
5863 // Configuration initialization
5864 config
= config
|| {};
5867 this.popup
= new OO
.ui
.PopupWidget( $.extend(
5870 $floatableContainer
: this.$element
5874 $autoCloseIgnore
: this.$element
.add( config
.popup
&& config
.popup
.$autoCloseIgnore
)
5884 * @return {OO.ui.PopupWidget} Popup widget
5886 OO
.ui
.mixin
.PopupElement
.prototype.getPopup = function () {
5891 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
5892 * which is used to display additional information or options.
5895 * // Example of a popup button.
5896 * var popupButton = new OO.ui.PopupButtonWidget( {
5897 * label: 'Popup button with options',
5900 * $content: $( '<p>Additional options here.</p>' ),
5902 * align: 'force-left'
5905 * // Append the button to the DOM.
5906 * $( 'body' ).append( popupButton.$element );
5909 * @extends OO.ui.ButtonWidget
5910 * @mixins OO.ui.mixin.PopupElement
5913 * @param {Object} [config] Configuration options
5914 * @cfg {jQuery} [$overlay] Render the popup into a separate layer. This configuration is useful in cases where
5915 * the expanded popup is larger than its containing `<div>`. The specified overlay layer is usually on top of the
5916 * containing `<div>` and has a larger area. By default, the popup uses relative positioning.
5917 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
5919 OO
.ui
.PopupButtonWidget
= function OoUiPopupButtonWidget( config
) {
5920 // Configuration initialization
5921 config
= config
|| {};
5923 // Parent constructor
5924 OO
.ui
.PopupButtonWidget
.parent
.call( this, config
);
5926 // Mixin constructors
5927 OO
.ui
.mixin
.PopupElement
.call( this, config
);
5930 this.$overlay
= ( config
.$overlay
=== true ? OO
.ui
.getDefaultOverlay() : config
.$overlay
) || this.$element
;
5933 this.connect( this, { click
: 'onAction' } );
5937 .addClass( 'oo-ui-popupButtonWidget' );
5939 .addClass( 'oo-ui-popupButtonWidget-popup' )
5940 .toggleClass( 'oo-ui-popupButtonWidget-framed-popup', this.isFramed() )
5941 .toggleClass( 'oo-ui-popupButtonWidget-frameless-popup', !this.isFramed() );
5942 this.$overlay
.append( this.popup
.$element
);
5947 OO
.inheritClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.ButtonWidget
);
5948 OO
.mixinClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.mixin
.PopupElement
);
5953 * Handle the button action being triggered.
5957 OO
.ui
.PopupButtonWidget
.prototype.onAction = function () {
5958 this.popup
.toggle();
5962 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
5964 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
5969 * @mixins OO.ui.mixin.GroupElement
5972 * @param {Object} [config] Configuration options
5974 OO
.ui
.mixin
.GroupWidget
= function OoUiMixinGroupWidget( config
) {
5975 // Mixin constructors
5976 OO
.ui
.mixin
.GroupElement
.call( this, config
);
5981 OO
.mixinClass( OO
.ui
.mixin
.GroupWidget
, OO
.ui
.mixin
.GroupElement
);
5986 * Set the disabled state of the widget.
5988 * This will also update the disabled state of child widgets.
5990 * @param {boolean} disabled Disable widget
5993 OO
.ui
.mixin
.GroupWidget
.prototype.setDisabled = function ( disabled
) {
5997 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
5998 OO
.ui
.Widget
.prototype.setDisabled
.call( this, disabled
);
6000 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
6002 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6003 this.items
[ i
].updateDisabled();
6011 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
6013 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
6014 * allows bidirectional communication.
6016 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
6024 OO
.ui
.mixin
.ItemWidget
= function OoUiMixinItemWidget() {
6031 * Check if widget is disabled.
6033 * Checks parent if present, making disabled state inheritable.
6035 * @return {boolean} Widget is disabled
6037 OO
.ui
.mixin
.ItemWidget
.prototype.isDisabled = function () {
6038 return this.disabled
||
6039 ( this.elementGroup
instanceof OO
.ui
.Widget
&& this.elementGroup
.isDisabled() );
6043 * Set group element is in.
6045 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
6048 OO
.ui
.mixin
.ItemWidget
.prototype.setElementGroup = function ( group
) {
6050 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
6051 OO
.ui
.Element
.prototype.setElementGroup
.call( this, group
);
6053 // Initialize item disabled states
6054 this.updateDisabled();
6060 * OptionWidgets are special elements that can be selected and configured with data. The
6061 * data is often unique for each option, but it does not have to be. OptionWidgets are used
6062 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
6063 * and examples, please see the [OOUI documentation on MediaWiki][1].
6065 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
6068 * @extends OO.ui.Widget
6069 * @mixins OO.ui.mixin.ItemWidget
6070 * @mixins OO.ui.mixin.LabelElement
6071 * @mixins OO.ui.mixin.FlaggedElement
6072 * @mixins OO.ui.mixin.AccessKeyedElement
6075 * @param {Object} [config] Configuration options
6077 OO
.ui
.OptionWidget
= function OoUiOptionWidget( config
) {
6078 // Configuration initialization
6079 config
= config
|| {};
6081 // Parent constructor
6082 OO
.ui
.OptionWidget
.parent
.call( this, config
);
6084 // Mixin constructors
6085 OO
.ui
.mixin
.ItemWidget
.call( this );
6086 OO
.ui
.mixin
.LabelElement
.call( this, config
);
6087 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
6088 OO
.ui
.mixin
.AccessKeyedElement
.call( this, config
);
6091 this.selected
= false;
6092 this.highlighted
= false;
6093 this.pressed
= false;
6097 .data( 'oo-ui-optionWidget', this )
6098 // Allow programmatic focussing (and by accesskey), but not tabbing
6099 .attr( 'tabindex', '-1' )
6100 .attr( 'role', 'option' )
6101 .attr( 'aria-selected', 'false' )
6102 .addClass( 'oo-ui-optionWidget' )
6103 .append( this.$label
);
6108 OO
.inheritClass( OO
.ui
.OptionWidget
, OO
.ui
.Widget
);
6109 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.ItemWidget
);
6110 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.LabelElement
);
6111 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.FlaggedElement
);
6112 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
6114 /* Static Properties */
6117 * Whether this option can be selected. See #setSelected.
6121 * @property {boolean}
6123 OO
.ui
.OptionWidget
.static.selectable
= true;
6126 * Whether this option can be highlighted. See #setHighlighted.
6130 * @property {boolean}
6132 OO
.ui
.OptionWidget
.static.highlightable
= true;
6135 * Whether this option can be pressed. See #setPressed.
6139 * @property {boolean}
6141 OO
.ui
.OptionWidget
.static.pressable
= true;
6144 * Whether this option will be scrolled into view when it is selected.
6148 * @property {boolean}
6150 OO
.ui
.OptionWidget
.static.scrollIntoViewOnSelect
= false;
6155 * Check if the option can be selected.
6157 * @return {boolean} Item is selectable
6159 OO
.ui
.OptionWidget
.prototype.isSelectable = function () {
6160 return this.constructor.static.selectable
&& !this.disabled
&& this.isVisible();
6164 * Check if the option can be highlighted. A highlight indicates that the option
6165 * may be selected when a user presses enter or clicks. Disabled items cannot
6168 * @return {boolean} Item is highlightable
6170 OO
.ui
.OptionWidget
.prototype.isHighlightable = function () {
6171 return this.constructor.static.highlightable
&& !this.disabled
&& this.isVisible();
6175 * Check if the option can be pressed. The pressed state occurs when a user mouses
6176 * down on an item, but has not yet let go of the mouse.
6178 * @return {boolean} Item is pressable
6180 OO
.ui
.OptionWidget
.prototype.isPressable = function () {
6181 return this.constructor.static.pressable
&& !this.disabled
&& this.isVisible();
6185 * Check if the option is selected.
6187 * @return {boolean} Item is selected
6189 OO
.ui
.OptionWidget
.prototype.isSelected = function () {
6190 return this.selected
;
6194 * Check if the option is highlighted. A highlight indicates that the
6195 * item may be selected when a user presses enter or clicks.
6197 * @return {boolean} Item is highlighted
6199 OO
.ui
.OptionWidget
.prototype.isHighlighted = function () {
6200 return this.highlighted
;
6204 * Check if the option is pressed. The pressed state occurs when a user mouses
6205 * down on an item, but has not yet let go of the mouse. The item may appear
6206 * selected, but it will not be selected until the user releases the mouse.
6208 * @return {boolean} Item is pressed
6210 OO
.ui
.OptionWidget
.prototype.isPressed = function () {
6211 return this.pressed
;
6215 * Set the option’s selected state. In general, all modifications to the selection
6216 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
6217 * method instead of this method.
6219 * @param {boolean} [state=false] Select option
6222 OO
.ui
.OptionWidget
.prototype.setSelected = function ( state
) {
6223 if ( this.constructor.static.selectable
) {
6224 this.selected
= !!state
;
6226 .toggleClass( 'oo-ui-optionWidget-selected', state
)
6227 .attr( 'aria-selected', state
.toString() );
6228 if ( state
&& this.constructor.static.scrollIntoViewOnSelect
) {
6229 this.scrollElementIntoView();
6231 this.updateThemeClasses();
6237 * Set the option’s highlighted state. In general, all programmatic
6238 * modifications to the highlight should be handled by the
6239 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
6240 * method instead of this method.
6242 * @param {boolean} [state=false] Highlight option
6245 OO
.ui
.OptionWidget
.prototype.setHighlighted = function ( state
) {
6246 if ( this.constructor.static.highlightable
) {
6247 this.highlighted
= !!state
;
6248 this.$element
.toggleClass( 'oo-ui-optionWidget-highlighted', state
);
6249 this.updateThemeClasses();
6255 * Set the option’s pressed state. In general, all
6256 * programmatic modifications to the pressed state should be handled by the
6257 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
6258 * method instead of this method.
6260 * @param {boolean} [state=false] Press option
6263 OO
.ui
.OptionWidget
.prototype.setPressed = function ( state
) {
6264 if ( this.constructor.static.pressable
) {
6265 this.pressed
= !!state
;
6266 this.$element
.toggleClass( 'oo-ui-optionWidget-pressed', state
);
6267 this.updateThemeClasses();
6273 * Get text to match search strings against.
6275 * The default implementation returns the label text, but subclasses
6276 * can override this to provide more complex behavior.
6278 * @return {string|boolean} String to match search string against
6280 OO
.ui
.OptionWidget
.prototype.getMatchText = function () {
6281 var label
= this.getLabel();
6282 return typeof label
=== 'string' ? label
: this.$label
.text();
6286 * A SelectWidget is of a generic selection of options. The OOUI library contains several types of
6287 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
6288 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
6291 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
6292 * information, please see the [OOUI documentation on MediaWiki][1].
6295 * // Example of a select widget with three options
6296 * var select = new OO.ui.SelectWidget( {
6298 * new OO.ui.OptionWidget( {
6300 * label: 'Option One',
6302 * new OO.ui.OptionWidget( {
6304 * label: 'Option Two',
6306 * new OO.ui.OptionWidget( {
6308 * label: 'Option Three',
6312 * $( 'body' ).append( select.$element );
6314 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
6318 * @extends OO.ui.Widget
6319 * @mixins OO.ui.mixin.GroupWidget
6322 * @param {Object} [config] Configuration options
6323 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
6324 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
6325 * the [OOUI documentation on MediaWiki] [2] for examples.
6326 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
6328 OO
.ui
.SelectWidget
= function OoUiSelectWidget( config
) {
6329 // Configuration initialization
6330 config
= config
|| {};
6332 // Parent constructor
6333 OO
.ui
.SelectWidget
.parent
.call( this, config
);
6335 // Mixin constructors
6336 OO
.ui
.mixin
.GroupWidget
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
6339 this.pressed
= false;
6340 this.selecting
= null;
6341 this.onDocumentMouseUpHandler
= this.onDocumentMouseUp
.bind( this );
6342 this.onDocumentMouseMoveHandler
= this.onDocumentMouseMove
.bind( this );
6343 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
6344 this.onDocumentKeyPressHandler
= this.onDocumentKeyPress
.bind( this );
6345 this.keyPressBuffer
= '';
6346 this.keyPressBufferTimer
= null;
6347 this.blockMouseOverEvents
= 0;
6350 this.connect( this, {
6354 focusin
: this.onFocus
.bind( this ),
6355 mousedown
: this.onMouseDown
.bind( this ),
6356 mouseover
: this.onMouseOver
.bind( this ),
6357 mouseleave
: this.onMouseLeave
.bind( this )
6362 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
6363 .attr( 'role', 'listbox' );
6364 this.setFocusOwner( this.$element
);
6365 if ( Array
.isArray( config
.items
) ) {
6366 this.addItems( config
.items
);
6372 OO
.inheritClass( OO
.ui
.SelectWidget
, OO
.ui
.Widget
);
6373 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupWidget
);
6380 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
6382 * @param {OO.ui.OptionWidget|null} item Highlighted item
6388 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
6389 * pressed state of an option.
6391 * @param {OO.ui.OptionWidget|null} item Pressed item
6397 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
6399 * @param {OO.ui.OptionWidget|null} item Selected item
6404 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
6405 * @param {OO.ui.OptionWidget} item Chosen item
6411 * An `add` event is emitted when options are added to the select with the #addItems method.
6413 * @param {OO.ui.OptionWidget[]} items Added items
6414 * @param {number} index Index of insertion point
6420 * A `remove` event is emitted when options are removed from the select with the #clearItems
6421 * or #removeItems methods.
6423 * @param {OO.ui.OptionWidget[]} items Removed items
6429 * Handle focus events
6432 * @param {jQuery.Event} event
6434 OO
.ui
.SelectWidget
.prototype.onFocus = function ( event
) {
6436 if ( event
.target
=== this.$element
[ 0 ] ) {
6437 // This widget was focussed, e.g. by the user tabbing to it.
6438 // The styles for focus state depend on one of the items being selected.
6439 if ( !this.findSelectedItem() ) {
6440 item
= this.findFirstSelectableItem();
6443 if ( event
.target
.tabIndex
=== -1 ) {
6444 // One of the options got focussed (and the event bubbled up here).
6445 // They can't be tabbed to, but they can be activated using accesskeys.
6446 // OptionWidgets and focusable UI elements inside them have tabindex="-1" set.
6447 item
= this.findTargetItem( event
);
6449 // There is something actually user-focusable in one of the labels of the options, and the
6450 // user focussed it (e.g. by tabbing to it). Do nothing (especially, don't change the focus).
6456 if ( item
.constructor.static.highlightable
) {
6457 this.highlightItem( item
);
6459 this.selectItem( item
);
6463 if ( event
.target
!== this.$element
[ 0 ] ) {
6464 this.$focusOwner
.focus();
6469 * Handle mouse down events.
6472 * @param {jQuery.Event} e Mouse down event
6474 OO
.ui
.SelectWidget
.prototype.onMouseDown = function ( e
) {
6477 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
6478 this.togglePressed( true );
6479 item
= this.findTargetItem( e
);
6480 if ( item
&& item
.isSelectable() ) {
6481 this.pressItem( item
);
6482 this.selecting
= item
;
6483 this.getElementDocument().addEventListener( 'mouseup', this.onDocumentMouseUpHandler
, true );
6484 this.getElementDocument().addEventListener( 'mousemove', this.onDocumentMouseMoveHandler
, true );
6491 * Handle document mouse up events.
6494 * @param {MouseEvent} e Mouse up event
6496 OO
.ui
.SelectWidget
.prototype.onDocumentMouseUp = function ( e
) {
6499 this.togglePressed( false );
6500 if ( !this.selecting
) {
6501 item
= this.findTargetItem( e
);
6502 if ( item
&& item
.isSelectable() ) {
6503 this.selecting
= item
;
6506 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
&& this.selecting
) {
6507 this.pressItem( null );
6508 this.chooseItem( this.selecting
);
6509 this.selecting
= null;
6512 this.getElementDocument().removeEventListener( 'mouseup', this.onDocumentMouseUpHandler
, true );
6513 this.getElementDocument().removeEventListener( 'mousemove', this.onDocumentMouseMoveHandler
, true );
6518 // Deprecated alias since 0.28.3
6519 OO
.ui
.SelectWidget
.prototype.onMouseUp = function () {
6520 OO
.ui
.warnDeprecation( 'onMouseUp is deprecated, use onDocumentMouseUp instead' );
6521 this.onDocumentMouseUp
.apply( this, arguments
);
6525 * Handle document mouse move events.
6528 * @param {MouseEvent} e Mouse move event
6530 OO
.ui
.SelectWidget
.prototype.onDocumentMouseMove = function ( e
) {
6533 if ( !this.isDisabled() && this.pressed
) {
6534 item
= this.findTargetItem( e
);
6535 if ( item
&& item
!== this.selecting
&& item
.isSelectable() ) {
6536 this.pressItem( item
);
6537 this.selecting
= item
;
6542 // Deprecated alias since 0.28.3
6543 OO
.ui
.SelectWidget
.prototype.onMouseMove = function () {
6544 OO
.ui
.warnDeprecation( 'onMouseMove is deprecated, use onDocumentMouseMove instead' );
6545 this.onDocumentMouseMove
.apply( this, arguments
);
6549 * Handle mouse over events.
6552 * @param {jQuery.Event} e Mouse over event
6554 OO
.ui
.SelectWidget
.prototype.onMouseOver = function ( e
) {
6556 if ( this.blockMouseOverEvents
) {
6559 if ( !this.isDisabled() ) {
6560 item
= this.findTargetItem( e
);
6561 this.highlightItem( item
&& item
.isHighlightable() ? item
: null );
6567 * Handle mouse leave events.
6570 * @param {jQuery.Event} e Mouse over event
6572 OO
.ui
.SelectWidget
.prototype.onMouseLeave = function () {
6573 if ( !this.isDisabled() ) {
6574 this.highlightItem( null );
6580 * Handle document key down events.
6583 * @param {KeyboardEvent} e Key down event
6585 OO
.ui
.SelectWidget
.prototype.onDocumentKeyDown = function ( e
) {
6588 currentItem
= this.findHighlightedItem() || this.findSelectedItem();
6590 if ( !this.isDisabled() && this.isVisible() ) {
6591 switch ( e
.keyCode
) {
6592 case OO
.ui
.Keys
.ENTER
:
6593 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
6594 // Was only highlighted, now let's select it. No-op if already selected.
6595 this.chooseItem( currentItem
);
6600 case OO
.ui
.Keys
.LEFT
:
6601 this.clearKeyPressBuffer();
6602 nextItem
= this.findRelativeSelectableItem( currentItem
, -1 );
6605 case OO
.ui
.Keys
.DOWN
:
6606 case OO
.ui
.Keys
.RIGHT
:
6607 this.clearKeyPressBuffer();
6608 nextItem
= this.findRelativeSelectableItem( currentItem
, 1 );
6611 case OO
.ui
.Keys
.ESCAPE
:
6612 case OO
.ui
.Keys
.TAB
:
6613 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
6614 currentItem
.setHighlighted( false );
6616 this.unbindDocumentKeyDownListener();
6617 this.unbindDocumentKeyPressListener();
6618 // Don't prevent tabbing away / defocusing
6624 if ( nextItem
.constructor.static.highlightable
) {
6625 this.highlightItem( nextItem
);
6627 this.chooseItem( nextItem
);
6629 this.scrollItemIntoView( nextItem
);
6634 e
.stopPropagation();
6639 // Deprecated alias since 0.28.3
6640 OO
.ui
.SelectWidget
.prototype.onKeyDown = function () {
6641 OO
.ui
.warnDeprecation( 'onKeyDown is deprecated, use onDocumentKeyDown instead' );
6642 this.onDocumentKeyDown
.apply( this, arguments
);
6646 * Bind document key down listener.
6650 OO
.ui
.SelectWidget
.prototype.bindDocumentKeyDownListener = function () {
6651 this.getElementDocument().addEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
6654 // Deprecated alias since 0.28.3
6655 OO
.ui
.SelectWidget
.prototype.bindKeyDownListener = function () {
6656 OO
.ui
.warnDeprecation( 'bindKeyDownListener is deprecated, use bindDocumentKeyDownListener instead' );
6657 this.bindDocumentKeyDownListener
.apply( this, arguments
);
6661 * Unbind document key down listener.
6665 OO
.ui
.SelectWidget
.prototype.unbindDocumentKeyDownListener = function () {
6666 this.getElementDocument().removeEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
6669 // Deprecated alias since 0.28.3
6670 OO
.ui
.SelectWidget
.prototype.unbindKeyDownListener = function () {
6671 OO
.ui
.warnDeprecation( 'unbindKeyDownListener is deprecated, use unbindDocumentKeyDownListener instead' );
6672 this.unbindDocumentKeyDownListener
.apply( this, arguments
);
6676 * Scroll item into view, preventing spurious mouse highlight actions from happening.
6678 * @param {OO.ui.OptionWidget} item Item to scroll into view
6680 OO
.ui
.SelectWidget
.prototype.scrollItemIntoView = function ( item
) {
6682 // Chromium's Blink engine will generate spurious 'mouseover' events during programmatic scrolling
6683 // and around 100-150 ms after it is finished.
6684 this.blockMouseOverEvents
++;
6685 item
.scrollElementIntoView().done( function () {
6686 setTimeout( function () {
6687 widget
.blockMouseOverEvents
--;
6693 * Clear the key-press buffer
6697 OO
.ui
.SelectWidget
.prototype.clearKeyPressBuffer = function () {
6698 if ( this.keyPressBufferTimer
) {
6699 clearTimeout( this.keyPressBufferTimer
);
6700 this.keyPressBufferTimer
= null;
6702 this.keyPressBuffer
= '';
6706 * Handle key press events.
6709 * @param {KeyboardEvent} e Key press event
6711 OO
.ui
.SelectWidget
.prototype.onDocumentKeyPress = function ( e
) {
6712 var c
, filter
, item
;
6714 if ( !e
.charCode
) {
6715 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
&& this.keyPressBuffer
!== '' ) {
6716 this.keyPressBuffer
= this.keyPressBuffer
.substr( 0, this.keyPressBuffer
.length
- 1 );
6721 if ( String
.fromCodePoint
) {
6722 c
= String
.fromCodePoint( e
.charCode
);
6724 c
= String
.fromCharCode( e
.charCode
);
6727 if ( this.keyPressBufferTimer
) {
6728 clearTimeout( this.keyPressBufferTimer
);
6730 this.keyPressBufferTimer
= setTimeout( this.clearKeyPressBuffer
.bind( this ), 1500 );
6732 item
= this.findHighlightedItem() || this.findSelectedItem();
6734 if ( this.keyPressBuffer
=== c
) {
6735 // Common (if weird) special case: typing "xxxx" will cycle through all
6736 // the items beginning with "x".
6738 item
= this.findRelativeSelectableItem( item
, 1 );
6741 this.keyPressBuffer
+= c
;
6744 filter
= this.getItemMatcher( this.keyPressBuffer
, false );
6745 if ( !item
|| !filter( item
) ) {
6746 item
= this.findRelativeSelectableItem( item
, 1, filter
);
6749 if ( this.isVisible() && item
.constructor.static.highlightable
) {
6750 this.highlightItem( item
);
6752 this.chooseItem( item
);
6754 this.scrollItemIntoView( item
);
6758 e
.stopPropagation();
6761 // Deprecated alias since 0.28.3
6762 OO
.ui
.SelectWidget
.prototype.onKeyPress = function () {
6763 OO
.ui
.warnDeprecation( 'onKeyPress is deprecated, use onDocumentKeyPress instead' );
6764 this.onDocumentKeyPress
.apply( this, arguments
);
6768 * Get a matcher for the specific string
6771 * @param {string} s String to match against items
6772 * @param {boolean} [exact=false] Only accept exact matches
6773 * @return {Function} function ( OO.ui.OptionWidget ) => boolean
6775 OO
.ui
.SelectWidget
.prototype.getItemMatcher = function ( s
, exact
) {
6778 if ( s
.normalize
) {
6781 s
= exact
? s
.trim() : s
.replace( /^\s+/, '' );
6782 re
= '^\\s*' + s
.replace( /([\\{}()|.?*+\-^$[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
6786 re
= new RegExp( re
, 'i' );
6787 return function ( item
) {
6788 var matchText
= item
.getMatchText();
6789 if ( matchText
.normalize
) {
6790 matchText
= matchText
.normalize();
6792 return re
.test( matchText
);
6797 * Bind document key press listener.
6801 OO
.ui
.SelectWidget
.prototype.bindDocumentKeyPressListener = function () {
6802 this.getElementDocument().addEventListener( 'keypress', this.onDocumentKeyPressHandler
, true );
6805 // Deprecated alias since 0.28.3
6806 OO
.ui
.SelectWidget
.prototype.bindKeyPressListener = function () {
6807 OO
.ui
.warnDeprecation( 'bindKeyPressListener is deprecated, use bindDocumentKeyPressListener instead' );
6808 this.bindDocumentKeyPressListener
.apply( this, arguments
);
6812 * Unbind document key down listener.
6814 * If you override this, be sure to call this.clearKeyPressBuffer() from your
6819 OO
.ui
.SelectWidget
.prototype.unbindDocumentKeyPressListener = function () {
6820 this.getElementDocument().removeEventListener( 'keypress', this.onDocumentKeyPressHandler
, true );
6821 this.clearKeyPressBuffer();
6824 // Deprecated alias since 0.28.3
6825 OO
.ui
.SelectWidget
.prototype.unbindKeyPressListener = function () {
6826 OO
.ui
.warnDeprecation( 'unbindKeyPressListener is deprecated, use unbindDocumentKeyPressListener instead' );
6827 this.unbindDocumentKeyPressListener
.apply( this, arguments
);
6831 * Visibility change handler
6834 * @param {boolean} visible
6836 OO
.ui
.SelectWidget
.prototype.onToggle = function ( visible
) {
6838 this.clearKeyPressBuffer();
6843 * Get the closest item to a jQuery.Event.
6846 * @param {jQuery.Event} e
6847 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
6849 OO
.ui
.SelectWidget
.prototype.findTargetItem = function ( e
) {
6850 var $option
= $( e
.target
).closest( '.oo-ui-optionWidget' );
6851 if ( !$option
.closest( '.oo-ui-selectWidget' ).is( this.$element
) ) {
6854 return $option
.data( 'oo-ui-optionWidget' ) || null;
6858 * Find selected item.
6860 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
6862 OO
.ui
.SelectWidget
.prototype.findSelectedItem = function () {
6865 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6866 if ( this.items
[ i
].isSelected() ) {
6867 return this.items
[ i
];
6874 * Find highlighted item.
6876 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
6878 OO
.ui
.SelectWidget
.prototype.findHighlightedItem = function () {
6881 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6882 if ( this.items
[ i
].isHighlighted() ) {
6883 return this.items
[ i
];
6890 * Toggle pressed state.
6892 * Press is a state that occurs when a user mouses down on an item, but
6893 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
6894 * until the user releases the mouse.
6896 * @param {boolean} pressed An option is being pressed
6898 OO
.ui
.SelectWidget
.prototype.togglePressed = function ( pressed
) {
6899 if ( pressed
=== undefined ) {
6900 pressed
= !this.pressed
;
6902 if ( pressed
!== this.pressed
) {
6904 .toggleClass( 'oo-ui-selectWidget-pressed', pressed
)
6905 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed
);
6906 this.pressed
= pressed
;
6911 * Highlight an option. If the `item` param is omitted, no options will be highlighted
6912 * and any existing highlight will be removed. The highlight is mutually exclusive.
6914 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
6918 OO
.ui
.SelectWidget
.prototype.highlightItem = function ( item
) {
6919 var i
, len
, highlighted
,
6922 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6923 highlighted
= this.items
[ i
] === item
;
6924 if ( this.items
[ i
].isHighlighted() !== highlighted
) {
6925 this.items
[ i
].setHighlighted( highlighted
);
6931 this.$focusOwner
.attr( 'aria-activedescendant', item
.getElementId() );
6933 this.$focusOwner
.removeAttr( 'aria-activedescendant' );
6935 this.emit( 'highlight', item
);
6942 * Fetch an item by its label.
6944 * @param {string} label Label of the item to select.
6945 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
6946 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
6948 OO
.ui
.SelectWidget
.prototype.getItemFromLabel = function ( label
, prefix
) {
6950 len
= this.items
.length
,
6951 filter
= this.getItemMatcher( label
, true );
6953 for ( i
= 0; i
< len
; i
++ ) {
6954 item
= this.items
[ i
];
6955 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
6962 filter
= this.getItemMatcher( label
, false );
6963 for ( i
= 0; i
< len
; i
++ ) {
6964 item
= this.items
[ i
];
6965 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
6981 * Programmatically select an option by its label. If the item does not exist,
6982 * all options will be deselected.
6984 * @param {string} [label] Label of the item to select.
6985 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
6989 OO
.ui
.SelectWidget
.prototype.selectItemByLabel = function ( label
, prefix
) {
6990 var itemFromLabel
= this.getItemFromLabel( label
, !!prefix
);
6991 if ( label
=== undefined || !itemFromLabel
) {
6992 return this.selectItem();
6994 return this.selectItem( itemFromLabel
);
6998 * Programmatically select an option by its data. If the `data` parameter is omitted,
6999 * or if the item does not exist, all options will be deselected.
7001 * @param {Object|string} [data] Value of the item to select, omit to deselect all
7005 OO
.ui
.SelectWidget
.prototype.selectItemByData = function ( data
) {
7006 var itemFromData
= this.findItemFromData( data
);
7007 if ( data
=== undefined || !itemFromData
) {
7008 return this.selectItem();
7010 return this.selectItem( itemFromData
);
7014 * Programmatically select an option by its reference. If the `item` parameter is omitted,
7015 * all options will be deselected.
7017 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
7021 OO
.ui
.SelectWidget
.prototype.selectItem = function ( item
) {
7022 var i
, len
, selected
,
7025 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
7026 selected
= this.items
[ i
] === item
;
7027 if ( this.items
[ i
].isSelected() !== selected
) {
7028 this.items
[ i
].setSelected( selected
);
7033 if ( item
&& !item
.constructor.static.highlightable
) {
7035 this.$focusOwner
.attr( 'aria-activedescendant', item
.getElementId() );
7037 this.$focusOwner
.removeAttr( 'aria-activedescendant' );
7040 this.emit( 'select', item
);
7049 * Press is a state that occurs when a user mouses down on an item, but has not
7050 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
7051 * releases the mouse.
7053 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
7057 OO
.ui
.SelectWidget
.prototype.pressItem = function ( item
) {
7058 var i
, len
, pressed
,
7061 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
7062 pressed
= this.items
[ i
] === item
;
7063 if ( this.items
[ i
].isPressed() !== pressed
) {
7064 this.items
[ i
].setPressed( pressed
);
7069 this.emit( 'press', item
);
7078 * Note that ‘choose’ should never be modified programmatically. A user can choose
7079 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
7080 * use the #selectItem method.
7082 * This method is identical to #selectItem, but may vary in subclasses that take additional action
7083 * when users choose an item with the keyboard or mouse.
7085 * @param {OO.ui.OptionWidget} item Item to choose
7089 OO
.ui
.SelectWidget
.prototype.chooseItem = function ( item
) {
7091 this.selectItem( item
);
7092 this.emit( 'choose', item
);
7099 * Find an option by its position relative to the specified item (or to the start of the option array,
7100 * if item is `null`). The direction in which to search through the option array is specified with a
7101 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
7102 * `null` if there are no options in the array.
7104 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
7105 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
7106 * @param {Function} [filter] Only consider items for which this function returns
7107 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
7108 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
7110 OO
.ui
.SelectWidget
.prototype.findRelativeSelectableItem = function ( item
, direction
, filter
) {
7111 var currentIndex
, nextIndex
, i
,
7112 increase
= direction
> 0 ? 1 : -1,
7113 len
= this.items
.length
;
7115 if ( item
instanceof OO
.ui
.OptionWidget
) {
7116 currentIndex
= this.items
.indexOf( item
);
7117 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
7119 // If no item is selected and moving forward, start at the beginning.
7120 // If moving backward, start at the end.
7121 nextIndex
= direction
> 0 ? 0 : len
- 1;
7124 for ( i
= 0; i
< len
; i
++ ) {
7125 item
= this.items
[ nextIndex
];
7127 item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() &&
7128 ( !filter
|| filter( item
) )
7132 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
7138 * Find the next selectable item or `null` if there are no selectable items.
7139 * Disabled options and menu-section markers and breaks are not selectable.
7141 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
7143 OO
.ui
.SelectWidget
.prototype.findFirstSelectableItem = function () {
7144 return this.findRelativeSelectableItem( null, 1 );
7148 * Add an array of options to the select. Optionally, an index number can be used to
7149 * specify an insertion point.
7151 * @param {OO.ui.OptionWidget[]} items Items to add
7152 * @param {number} [index] Index to insert items after
7156 OO
.ui
.SelectWidget
.prototype.addItems = function ( items
, index
) {
7158 OO
.ui
.mixin
.GroupWidget
.prototype.addItems
.call( this, items
, index
);
7160 // Always provide an index, even if it was omitted
7161 this.emit( 'add', items
, index
=== undefined ? this.items
.length
- items
.length
- 1 : index
);
7167 * Remove the specified array of options from the select. Options will be detached
7168 * from the DOM, not removed, so they can be reused later. To remove all options from
7169 * the select, you may wish to use the #clearItems method instead.
7171 * @param {OO.ui.OptionWidget[]} items Items to remove
7175 OO
.ui
.SelectWidget
.prototype.removeItems = function ( items
) {
7178 // Deselect items being removed
7179 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
7181 if ( item
.isSelected() ) {
7182 this.selectItem( null );
7187 OO
.ui
.mixin
.GroupWidget
.prototype.removeItems
.call( this, items
);
7189 this.emit( 'remove', items
);
7195 * Clear all options from the select. Options will be detached from the DOM, not removed,
7196 * so that they can be reused later. To remove a subset of options from the select, use
7197 * the #removeItems method.
7202 OO
.ui
.SelectWidget
.prototype.clearItems = function () {
7203 var items
= this.items
.slice();
7206 OO
.ui
.mixin
.GroupWidget
.prototype.clearItems
.call( this );
7209 this.selectItem( null );
7211 this.emit( 'remove', items
);
7217 * Set the DOM element which has focus while the user is interacting with this SelectWidget.
7219 * Currently this is just used to set `aria-activedescendant` on it.
7222 * @param {jQuery} $focusOwner
7224 OO
.ui
.SelectWidget
.prototype.setFocusOwner = function ( $focusOwner
) {
7225 this.$focusOwner
= $focusOwner
;
7229 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
7230 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
7231 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
7232 * options. For more information about options and selects, please see the
7233 * [OOUI documentation on MediaWiki][1].
7236 * // Decorated options in a select widget
7237 * var select = new OO.ui.SelectWidget( {
7239 * new OO.ui.DecoratedOptionWidget( {
7241 * label: 'Option with icon',
7244 * new OO.ui.DecoratedOptionWidget( {
7246 * label: 'Option with indicator',
7251 * $( 'body' ).append( select.$element );
7253 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
7256 * @extends OO.ui.OptionWidget
7257 * @mixins OO.ui.mixin.IconElement
7258 * @mixins OO.ui.mixin.IndicatorElement
7261 * @param {Object} [config] Configuration options
7263 OO
.ui
.DecoratedOptionWidget
= function OoUiDecoratedOptionWidget( config
) {
7264 // Parent constructor
7265 OO
.ui
.DecoratedOptionWidget
.parent
.call( this, config
);
7267 // Mixin constructors
7268 OO
.ui
.mixin
.IconElement
.call( this, config
);
7269 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
7273 .addClass( 'oo-ui-decoratedOptionWidget' )
7274 .prepend( this.$icon
)
7275 .append( this.$indicator
);
7280 OO
.inheritClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.OptionWidget
);
7281 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IconElement
);
7282 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IndicatorElement
);
7285 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
7286 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
7287 * the [OOUI documentation on MediaWiki] [1] for more information.
7289 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
7292 * @extends OO.ui.DecoratedOptionWidget
7295 * @param {Object} [config] Configuration options
7297 OO
.ui
.MenuOptionWidget
= function OoUiMenuOptionWidget( config
) {
7298 // Parent constructor
7299 OO
.ui
.MenuOptionWidget
.parent
.call( this, config
);
7302 this.checkIcon
= new OO
.ui
.IconWidget( {
7304 classes
: [ 'oo-ui-menuOptionWidget-checkIcon' ]
7309 .prepend( this.checkIcon
.$element
)
7310 .addClass( 'oo-ui-menuOptionWidget' );
7315 OO
.inheritClass( OO
.ui
.MenuOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
7317 /* Static Properties */
7323 OO
.ui
.MenuOptionWidget
.static.scrollIntoViewOnSelect
= true;
7326 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
7327 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
7330 * var myDropdown = new OO.ui.DropdownWidget( {
7333 * new OO.ui.MenuSectionOptionWidget( {
7336 * new OO.ui.MenuOptionWidget( {
7338 * label: 'Welsh Corgi'
7340 * new OO.ui.MenuOptionWidget( {
7342 * label: 'Standard Poodle'
7344 * new OO.ui.MenuSectionOptionWidget( {
7347 * new OO.ui.MenuOptionWidget( {
7354 * $( 'body' ).append( myDropdown.$element );
7357 * @extends OO.ui.DecoratedOptionWidget
7360 * @param {Object} [config] Configuration options
7362 OO
.ui
.MenuSectionOptionWidget
= function OoUiMenuSectionOptionWidget( config
) {
7363 // Parent constructor
7364 OO
.ui
.MenuSectionOptionWidget
.parent
.call( this, config
);
7367 this.$element
.addClass( 'oo-ui-menuSectionOptionWidget' )
7368 .removeAttr( 'role aria-selected' );
7373 OO
.inheritClass( OO
.ui
.MenuSectionOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
7375 /* Static Properties */
7381 OO
.ui
.MenuSectionOptionWidget
.static.selectable
= false;
7387 OO
.ui
.MenuSectionOptionWidget
.static.highlightable
= false;
7390 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
7391 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
7392 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget},
7393 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
7394 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
7395 * and customized to be opened, closed, and displayed as needed.
7397 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
7398 * mouse outside the menu.
7400 * Menus also have support for keyboard interaction:
7402 * - Enter/Return key: choose and select a menu option
7403 * - Up-arrow key: highlight the previous menu option
7404 * - Down-arrow key: highlight the next menu option
7405 * - Esc key: hide the menu
7407 * Unlike most widgets, MenuSelectWidget is initially hidden and must be shown by calling #toggle.
7409 * Please see the [OOUI documentation on MediaWiki][1] for more information.
7410 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
7413 * @extends OO.ui.SelectWidget
7414 * @mixins OO.ui.mixin.ClippableElement
7415 * @mixins OO.ui.mixin.FloatableElement
7418 * @param {Object} [config] Configuration options
7419 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
7420 * the text the user types. This config is used by {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}
7421 * and {@link OO.ui.mixin.LookupElement LookupElement}
7422 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
7423 * the text the user types. This config is used by {@link OO.ui.TagMultiselectWidget TagMultiselectWidget}
7424 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
7425 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
7426 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
7427 * that button, unless the button (or its parent widget) is passed in here.
7428 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
7429 * @cfg {jQuery} [$autoCloseIgnore] If these elements are clicked, don't auto-hide the menu.
7430 * @cfg {boolean} [hideOnChoose=true] Hide the menu when the user chooses an option.
7431 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
7432 * @cfg {boolean} [highlightOnFilter] Highlight the first result when filtering
7433 * @cfg {number} [width] Width of the menu
7435 OO
.ui
.MenuSelectWidget
= function OoUiMenuSelectWidget( config
) {
7436 // Configuration initialization
7437 config
= config
|| {};
7439 // Parent constructor
7440 OO
.ui
.MenuSelectWidget
.parent
.call( this, config
);
7442 // Mixin constructors
7443 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
7444 OO
.ui
.mixin
.FloatableElement
.call( this, config
);
7446 // Initial vertical positions other than 'center' will result in
7447 // the menu being flipped if there is not enough space in the container.
7448 // Store the original position so we know what to reset to.
7449 this.originalVerticalPosition
= this.verticalPosition
;
7452 this.autoHide
= config
.autoHide
=== undefined || !!config
.autoHide
;
7453 this.hideOnChoose
= config
.hideOnChoose
=== undefined || !!config
.hideOnChoose
;
7454 this.filterFromInput
= !!config
.filterFromInput
;
7455 this.$input
= config
.$input
? config
.$input
: config
.input
? config
.input
.$input
: null;
7456 this.$widget
= config
.widget
? config
.widget
.$element
: null;
7457 this.$autoCloseIgnore
= config
.$autoCloseIgnore
|| $( [] );
7458 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
7459 this.onInputEditHandler
= OO
.ui
.debounce( this.updateItemVisibility
.bind( this ), 100 );
7460 this.highlightOnFilter
= !!config
.highlightOnFilter
;
7461 this.width
= config
.width
;
7464 this.$element
.addClass( 'oo-ui-menuSelectWidget' );
7465 if ( config
.widget
) {
7466 this.setFocusOwner( config
.widget
.$tabIndexed
);
7469 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
7470 // that reference properties not initialized at that time of parent class construction
7471 // TODO: Find a better way to handle post-constructor setup
7472 this.visible
= false;
7473 this.$element
.addClass( 'oo-ui-element-hidden' );
7478 OO
.inheritClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.SelectWidget
);
7479 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.ClippableElement
);
7480 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.FloatableElement
);
7487 * The menu is ready: it is visible and has been positioned and clipped.
7490 /* Static properties */
7493 * Positions to flip to if there isn't room in the container for the
7494 * menu in a specific direction.
7496 * @property {Object.<string,string>}
7498 OO
.ui
.MenuSelectWidget
.static.flippedPositions
= {
7508 * Handles document mouse down events.
7511 * @param {MouseEvent} e Mouse down event
7513 OO
.ui
.MenuSelectWidget
.prototype.onDocumentMouseDown = function ( e
) {
7517 this.$element
.add( this.$widget
).add( this.$autoCloseIgnore
).get(),
7522 this.toggle( false );
7529 OO
.ui
.MenuSelectWidget
.prototype.onDocumentKeyDown = function ( e
) {
7530 var currentItem
= this.findHighlightedItem() || this.findSelectedItem();
7532 if ( !this.isDisabled() && this.isVisible() ) {
7533 switch ( e
.keyCode
) {
7534 case OO
.ui
.Keys
.LEFT
:
7535 case OO
.ui
.Keys
.RIGHT
:
7536 // Do nothing if a text field is associated, arrow keys will be handled natively
7537 if ( !this.$input
) {
7538 OO
.ui
.MenuSelectWidget
.parent
.prototype.onDocumentKeyDown
.call( this, e
);
7541 case OO
.ui
.Keys
.ESCAPE
:
7542 case OO
.ui
.Keys
.TAB
:
7543 if ( currentItem
) {
7544 currentItem
.setHighlighted( false );
7546 this.toggle( false );
7547 // Don't prevent tabbing away, prevent defocusing
7548 if ( e
.keyCode
=== OO
.ui
.Keys
.ESCAPE
) {
7550 e
.stopPropagation();
7554 OO
.ui
.MenuSelectWidget
.parent
.prototype.onDocumentKeyDown
.call( this, e
);
7561 * Update menu item visibility and clipping after input changes (if filterFromInput is enabled)
7562 * or after items were added/removed (always).
7566 OO
.ui
.MenuSelectWidget
.prototype.updateItemVisibility = function () {
7567 var i
, item
, items
, visible
, section
, sectionEmpty
, filter
, exactFilter
,
7569 len
= this.items
.length
,
7570 showAll
= !this.isVisible(),
7573 if ( this.$input
&& this.filterFromInput
) {
7574 filter
= showAll
? null : this.getItemMatcher( this.$input
.val() );
7575 exactFilter
= this.getItemMatcher( this.$input
.val(), true );
7576 // Hide non-matching options, and also hide section headers if all options
7577 // in their section are hidden.
7578 for ( i
= 0; i
< len
; i
++ ) {
7579 item
= this.items
[ i
];
7580 if ( item
instanceof OO
.ui
.MenuSectionOptionWidget
) {
7582 // If the previous section was empty, hide its header
7583 section
.toggle( showAll
|| !sectionEmpty
);
7586 sectionEmpty
= true;
7587 } else if ( item
instanceof OO
.ui
.OptionWidget
) {
7588 visible
= showAll
|| filter( item
);
7589 exactMatch
= exactMatch
|| exactFilter( item
);
7590 anyVisible
= anyVisible
|| visible
;
7591 sectionEmpty
= sectionEmpty
&& !visible
;
7592 item
.toggle( visible
);
7595 // Process the final section
7597 section
.toggle( showAll
|| !sectionEmpty
);
7600 if ( anyVisible
&& this.items
.length
&& !exactMatch
) {
7601 this.scrollItemIntoView( this.items
[ 0 ] );
7604 this.$element
.toggleClass( 'oo-ui-menuSelectWidget-invisible', !anyVisible
);
7606 if ( this.highlightOnFilter
) {
7607 // Highlight the first item on the list
7609 items
= this.getItems();
7610 for ( i
= 0; i
< items
.length
; i
++ ) {
7611 if ( items
[ i
].isVisible() ) {
7616 this.highlightItem( item
);
7621 // Reevaluate clipping
7628 OO
.ui
.MenuSelectWidget
.prototype.bindDocumentKeyDownListener = function () {
7629 if ( this.$input
) {
7630 this.$input
.on( 'keydown', this.onDocumentKeyDownHandler
);
7632 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindDocumentKeyDownListener
.call( this );
7639 OO
.ui
.MenuSelectWidget
.prototype.unbindDocumentKeyDownListener = function () {
7640 if ( this.$input
) {
7641 this.$input
.off( 'keydown', this.onDocumentKeyDownHandler
);
7643 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindDocumentKeyDownListener
.call( this );
7650 OO
.ui
.MenuSelectWidget
.prototype.bindDocumentKeyPressListener = function () {
7651 if ( this.$input
) {
7652 if ( this.filterFromInput
) {
7653 this.$input
.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
7654 this.updateItemVisibility();
7657 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindDocumentKeyPressListener
.call( this );
7664 OO
.ui
.MenuSelectWidget
.prototype.unbindDocumentKeyPressListener = function () {
7665 if ( this.$input
) {
7666 if ( this.filterFromInput
) {
7667 this.$input
.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
7668 this.updateItemVisibility();
7671 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindDocumentKeyPressListener
.call( this );
7678 * When a user chooses an item, the menu is closed, unless the hideOnChoose config option is set to false.
7680 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
7681 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
7683 * @param {OO.ui.OptionWidget} item Item to choose
7686 OO
.ui
.MenuSelectWidget
.prototype.chooseItem = function ( item
) {
7687 OO
.ui
.MenuSelectWidget
.parent
.prototype.chooseItem
.call( this, item
);
7688 if ( this.hideOnChoose
) {
7689 this.toggle( false );
7697 OO
.ui
.MenuSelectWidget
.prototype.addItems = function ( items
, index
) {
7699 OO
.ui
.MenuSelectWidget
.parent
.prototype.addItems
.call( this, items
, index
);
7701 this.updateItemVisibility();
7709 OO
.ui
.MenuSelectWidget
.prototype.removeItems = function ( items
) {
7711 OO
.ui
.MenuSelectWidget
.parent
.prototype.removeItems
.call( this, items
);
7713 this.updateItemVisibility();
7721 OO
.ui
.MenuSelectWidget
.prototype.clearItems = function () {
7723 OO
.ui
.MenuSelectWidget
.parent
.prototype.clearItems
.call( this );
7725 this.updateItemVisibility();
7731 * Toggle visibility of the menu. The menu is initially hidden and must be shown by calling
7732 * `.toggle( true )` after its #$element is attached to the DOM.
7734 * Do not show the menu while it is not attached to the DOM. The calculations required to display
7735 * it in the right place and with the right dimensions only work correctly while it is attached.
7736 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
7737 * strictly enforced, so currently it only generates a warning in the browser console.
7742 OO
.ui
.MenuSelectWidget
.prototype.toggle = function ( visible
) {
7743 var change
, originalHeight
, flippedHeight
;
7745 visible
= ( visible
=== undefined ? !this.visible
: !!visible
) && !!this.items
.length
;
7746 change
= visible
!== this.isVisible();
7748 if ( visible
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
7749 OO
.ui
.warnDeprecation( 'MenuSelectWidget#toggle: Before calling this method, the menu must be attached to the DOM.' );
7750 this.warnedUnattached
= true;
7753 if ( change
&& visible
) {
7754 // Reset position before showing the popup again. It's possible we no longer need to flip
7755 // (e.g. if the user scrolled).
7756 this.setVerticalPosition( this.originalVerticalPosition
);
7760 OO
.ui
.MenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
7766 this.setIdealSize( this.width
);
7767 } else if ( this.$floatableContainer
) {
7768 this.$clippable
.css( 'width', 'auto' );
7770 this.$floatableContainer
[ 0 ].offsetWidth
> this.$clippable
[ 0 ].offsetWidth
?
7771 // Dropdown is smaller than handle so expand to width
7772 this.$floatableContainer
[ 0 ].offsetWidth
:
7773 // Dropdown is larger than handle so auto size
7776 this.$clippable
.css( 'width', '' );
7779 this.togglePositioning( !!this.$floatableContainer
);
7780 this.toggleClipping( true );
7782 this.bindDocumentKeyDownListener();
7783 this.bindDocumentKeyPressListener();
7786 ( this.isClippedVertically() || this.isFloatableOutOfView() ) &&
7787 this.originalVerticalPosition
!== 'center'
7789 // If opening the menu in one direction causes it to be clipped, flip it
7790 originalHeight
= this.$element
.height();
7791 this.setVerticalPosition(
7792 this.constructor.static.flippedPositions
[ this.originalVerticalPosition
]
7794 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
7795 // If flipping also causes it to be clipped, open in whichever direction
7796 // we have more space
7797 flippedHeight
= this.$element
.height();
7798 if ( originalHeight
> flippedHeight
) {
7799 this.setVerticalPosition( this.originalVerticalPosition
);
7803 // Note that we do not flip the menu's opening direction if the clipping changes
7804 // later (e.g. after the user scrolls), that seems like it would be annoying
7806 this.$focusOwner
.attr( 'aria-expanded', 'true' );
7808 if ( this.findSelectedItem() ) {
7809 this.$focusOwner
.attr( 'aria-activedescendant', this.findSelectedItem().getElementId() );
7810 this.findSelectedItem().scrollElementIntoView( { duration
: 0 } );
7814 if ( this.autoHide
) {
7815 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
7818 this.emit( 'ready' );
7820 this.$focusOwner
.removeAttr( 'aria-activedescendant' );
7821 this.unbindDocumentKeyDownListener();
7822 this.unbindDocumentKeyPressListener();
7823 this.$focusOwner
.attr( 'aria-expanded', 'false' );
7824 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
7825 this.togglePositioning( false );
7826 this.toggleClipping( false );
7834 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
7835 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
7836 * users can interact with it.
7838 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7839 * OO.ui.DropdownInputWidget instead.
7842 * // Example: A DropdownWidget with a menu that contains three options
7843 * var dropDown = new OO.ui.DropdownWidget( {
7844 * label: 'Dropdown menu: Select a menu option',
7847 * new OO.ui.MenuOptionWidget( {
7851 * new OO.ui.MenuOptionWidget( {
7855 * new OO.ui.MenuOptionWidget( {
7863 * $( 'body' ).append( dropDown.$element );
7865 * dropDown.getMenu().selectItemByData( 'b' );
7867 * dropDown.getMenu().findSelectedItem().getData(); // returns 'b'
7869 * For more information, please see the [OOUI documentation on MediaWiki] [1].
7871 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
7874 * @extends OO.ui.Widget
7875 * @mixins OO.ui.mixin.IconElement
7876 * @mixins OO.ui.mixin.IndicatorElement
7877 * @mixins OO.ui.mixin.LabelElement
7878 * @mixins OO.ui.mixin.TitledElement
7879 * @mixins OO.ui.mixin.TabIndexedElement
7882 * @param {Object} [config] Configuration options
7883 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.MenuSelectWidget menu select widget}
7884 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
7885 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
7886 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
7887 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
7889 OO
.ui
.DropdownWidget
= function OoUiDropdownWidget( config
) {
7890 // Configuration initialization
7891 config
= $.extend( { indicator
: 'down' }, config
);
7893 // Parent constructor
7894 OO
.ui
.DropdownWidget
.parent
.call( this, config
);
7896 // Properties (must be set before TabIndexedElement constructor call)
7897 this.$handle
= $( '<span>' );
7898 this.$overlay
= ( config
.$overlay
=== true ? OO
.ui
.getDefaultOverlay() : config
.$overlay
) || this.$element
;
7900 // Mixin constructors
7901 OO
.ui
.mixin
.IconElement
.call( this, config
);
7902 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
7903 OO
.ui
.mixin
.LabelElement
.call( this, config
);
7904 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
7905 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
7908 this.menu
= new OO
.ui
.MenuSelectWidget( $.extend( {
7910 $floatableContainer
: this.$element
7915 click
: this.onClick
.bind( this ),
7916 keydown
: this.onKeyDown
.bind( this ),
7917 // Hack? Handle type-to-search when menu is not expanded and not handling its own events
7918 keypress
: this.menu
.onDocumentKeyPressHandler
,
7919 blur
: this.menu
.clearKeyPressBuffer
.bind( this.menu
)
7921 this.menu
.connect( this, {
7922 select
: 'onMenuSelect',
7923 toggle
: 'onMenuToggle'
7928 .addClass( 'oo-ui-dropdownWidget-handle' )
7931 'aria-owns': this.menu
.getElementId(),
7932 'aria-autocomplete': 'list'
7934 .append( this.$icon
, this.$label
, this.$indicator
);
7936 .addClass( 'oo-ui-dropdownWidget' )
7937 .append( this.$handle
);
7938 this.$overlay
.append( this.menu
.$element
);
7943 OO
.inheritClass( OO
.ui
.DropdownWidget
, OO
.ui
.Widget
);
7944 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IconElement
);
7945 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IndicatorElement
);
7946 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.LabelElement
);
7947 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TitledElement
);
7948 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TabIndexedElement
);
7955 * @return {OO.ui.MenuSelectWidget} Menu of widget
7957 OO
.ui
.DropdownWidget
.prototype.getMenu = function () {
7962 * Handles menu select events.
7965 * @param {OO.ui.MenuOptionWidget} item Selected menu item
7967 OO
.ui
.DropdownWidget
.prototype.onMenuSelect = function ( item
) {
7971 this.setLabel( null );
7975 selectedLabel
= item
.getLabel();
7977 // If the label is a DOM element, clone it, because setLabel will append() it
7978 if ( selectedLabel
instanceof jQuery
) {
7979 selectedLabel
= selectedLabel
.clone();
7982 this.setLabel( selectedLabel
);
7986 * Handle menu toggle events.
7989 * @param {boolean} isVisible Open state of the menu
7991 OO
.ui
.DropdownWidget
.prototype.onMenuToggle = function ( isVisible
) {
7992 this.$element
.toggleClass( 'oo-ui-dropdownWidget-open', isVisible
);
7995 this.$element
.hasClass( 'oo-ui-dropdownWidget-open' ).toString()
8000 * Handle mouse click events.
8003 * @param {jQuery.Event} e Mouse click event
8005 OO
.ui
.DropdownWidget
.prototype.onClick = function ( e
) {
8006 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
8013 * Handle key down events.
8016 * @param {jQuery.Event} e Key down event
8018 OO
.ui
.DropdownWidget
.prototype.onKeyDown = function ( e
) {
8020 !this.isDisabled() &&
8022 e
.which
=== OO
.ui
.Keys
.ENTER
||
8024 e
.which
=== OO
.ui
.Keys
.SPACE
&&
8025 // Avoid conflicts with type-to-search, see SelectWidget#onKeyPress.
8026 // Space only closes the menu is the user is not typing to search.
8027 this.menu
.keyPressBuffer
=== ''
8030 !this.menu
.isVisible() &&
8032 e
.which
=== OO
.ui
.Keys
.UP
||
8033 e
.which
=== OO
.ui
.Keys
.DOWN
8044 * RadioOptionWidget is an option widget that looks like a radio button.
8045 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
8046 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
8048 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Button_selects_and_option
8051 * @extends OO.ui.OptionWidget
8054 * @param {Object} [config] Configuration options
8056 OO
.ui
.RadioOptionWidget
= function OoUiRadioOptionWidget( config
) {
8057 // Configuration initialization
8058 config
= config
|| {};
8060 // Properties (must be done before parent constructor which calls #setDisabled)
8061 this.radio
= new OO
.ui
.RadioInputWidget( { value
: config
.data
, tabIndex
: -1 } );
8063 // Parent constructor
8064 OO
.ui
.RadioOptionWidget
.parent
.call( this, config
);
8067 // Remove implicit role, we're handling it ourselves
8068 this.radio
.$input
.attr( 'role', 'presentation' );
8070 .addClass( 'oo-ui-radioOptionWidget' )
8071 .attr( 'role', 'radio' )
8072 .attr( 'aria-checked', 'false' )
8073 .removeAttr( 'aria-selected' )
8074 .prepend( this.radio
.$element
);
8079 OO
.inheritClass( OO
.ui
.RadioOptionWidget
, OO
.ui
.OptionWidget
);
8081 /* Static Properties */
8087 OO
.ui
.RadioOptionWidget
.static.highlightable
= false;
8093 OO
.ui
.RadioOptionWidget
.static.scrollIntoViewOnSelect
= true;
8099 OO
.ui
.RadioOptionWidget
.static.pressable
= false;
8105 OO
.ui
.RadioOptionWidget
.static.tagName
= 'label';
8112 OO
.ui
.RadioOptionWidget
.prototype.setSelected = function ( state
) {
8113 OO
.ui
.RadioOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
8115 this.radio
.setSelected( state
);
8117 .attr( 'aria-checked', state
.toString() )
8118 .removeAttr( 'aria-selected' );
8126 OO
.ui
.RadioOptionWidget
.prototype.setDisabled = function ( disabled
) {
8127 OO
.ui
.RadioOptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
8129 this.radio
.setDisabled( this.isDisabled() );
8135 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
8136 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
8137 * an interface for adding, removing and selecting options.
8138 * Please see the [OOUI documentation on MediaWiki][1] for more information.
8140 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
8141 * OO.ui.RadioSelectInputWidget instead.
8144 * // A RadioSelectWidget with RadioOptions.
8145 * var option1 = new OO.ui.RadioOptionWidget( {
8147 * label: 'Selected radio option'
8150 * var option2 = new OO.ui.RadioOptionWidget( {
8152 * label: 'Unselected radio option'
8155 * var radioSelect=new OO.ui.RadioSelectWidget( {
8156 * items: [ option1, option2 ]
8159 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
8160 * radioSelect.selectItem( option1 );
8162 * $( 'body' ).append( radioSelect.$element );
8164 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
8168 * @extends OO.ui.SelectWidget
8169 * @mixins OO.ui.mixin.TabIndexedElement
8172 * @param {Object} [config] Configuration options
8174 OO
.ui
.RadioSelectWidget
= function OoUiRadioSelectWidget( config
) {
8175 // Parent constructor
8176 OO
.ui
.RadioSelectWidget
.parent
.call( this, config
);
8178 // Mixin constructors
8179 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
8183 focus
: this.bindDocumentKeyDownListener
.bind( this ),
8184 blur
: this.unbindDocumentKeyDownListener
.bind( this )
8189 .addClass( 'oo-ui-radioSelectWidget' )
8190 .attr( 'role', 'radiogroup' );
8195 OO
.inheritClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.SelectWidget
);
8196 OO
.mixinClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
8199 * MultioptionWidgets are special elements that can be selected and configured with data. The
8200 * data is often unique for each option, but it does not have to be. MultioptionWidgets are used
8201 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
8202 * and examples, please see the [OOUI documentation on MediaWiki][1].
8204 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Multioptions
8207 * @extends OO.ui.Widget
8208 * @mixins OO.ui.mixin.ItemWidget
8209 * @mixins OO.ui.mixin.LabelElement
8212 * @param {Object} [config] Configuration options
8213 * @cfg {boolean} [selected=false] Whether the option is initially selected
8215 OO
.ui
.MultioptionWidget
= function OoUiMultioptionWidget( config
) {
8216 // Configuration initialization
8217 config
= config
|| {};
8219 // Parent constructor
8220 OO
.ui
.MultioptionWidget
.parent
.call( this, config
);
8222 // Mixin constructors
8223 OO
.ui
.mixin
.ItemWidget
.call( this );
8224 OO
.ui
.mixin
.LabelElement
.call( this, config
);
8227 this.selected
= null;
8231 .addClass( 'oo-ui-multioptionWidget' )
8232 .append( this.$label
);
8233 this.setSelected( config
.selected
);
8238 OO
.inheritClass( OO
.ui
.MultioptionWidget
, OO
.ui
.Widget
);
8239 OO
.mixinClass( OO
.ui
.MultioptionWidget
, OO
.ui
.mixin
.ItemWidget
);
8240 OO
.mixinClass( OO
.ui
.MultioptionWidget
, OO
.ui
.mixin
.LabelElement
);
8247 * A change event is emitted when the selected state of the option changes.
8249 * @param {boolean} selected Whether the option is now selected
8255 * Check if the option is selected.
8257 * @return {boolean} Item is selected
8259 OO
.ui
.MultioptionWidget
.prototype.isSelected = function () {
8260 return this.selected
;
8264 * Set the option’s selected state. In general, all modifications to the selection
8265 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
8266 * method instead of this method.
8268 * @param {boolean} [state=false] Select option
8271 OO
.ui
.MultioptionWidget
.prototype.setSelected = function ( state
) {
8273 if ( this.selected
!== state
) {
8274 this.selected
= state
;
8275 this.emit( 'change', state
);
8276 this.$element
.toggleClass( 'oo-ui-multioptionWidget-selected', state
);
8282 * MultiselectWidget allows selecting multiple options from a list.
8284 * For more information about menus and options, please see the [OOUI documentation on MediaWiki][1].
8286 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
8290 * @extends OO.ui.Widget
8291 * @mixins OO.ui.mixin.GroupWidget
8294 * @param {Object} [config] Configuration options
8295 * @cfg {OO.ui.MultioptionWidget[]} [items] An array of options to add to the multiselect.
8297 OO
.ui
.MultiselectWidget
= function OoUiMultiselectWidget( config
) {
8298 // Parent constructor
8299 OO
.ui
.MultiselectWidget
.parent
.call( this, config
);
8301 // Configuration initialization
8302 config
= config
|| {};
8304 // Mixin constructors
8305 OO
.ui
.mixin
.GroupWidget
.call( this, config
);
8308 this.aggregate( { change
: 'select' } );
8309 // This is mostly for compatibility with TagMultiselectWidget... normally, 'change' is emitted
8310 // by GroupElement only when items are added/removed
8311 this.connect( this, { select
: [ 'emit', 'change' ] } );
8314 if ( config
.items
) {
8315 this.addItems( config
.items
);
8317 this.$group
.addClass( 'oo-ui-multiselectWidget-group' );
8318 this.$element
.addClass( 'oo-ui-multiselectWidget' )
8319 .append( this.$group
);
8324 OO
.inheritClass( OO
.ui
.MultiselectWidget
, OO
.ui
.Widget
);
8325 OO
.mixinClass( OO
.ui
.MultiselectWidget
, OO
.ui
.mixin
.GroupWidget
);
8332 * A change event is emitted when the set of items changes, or an item is selected or deselected.
8338 * A select event is emitted when an item is selected or deselected.
8344 * Find options that are selected.
8346 * @return {OO.ui.MultioptionWidget[]} Selected options
8348 OO
.ui
.MultiselectWidget
.prototype.findSelectedItems = function () {
8349 return this.items
.filter( function ( item
) {
8350 return item
.isSelected();
8355 * Find the data of options that are selected.
8357 * @return {Object[]|string[]} Values of selected options
8359 OO
.ui
.MultiselectWidget
.prototype.findSelectedItemsData = function () {
8360 return this.findSelectedItems().map( function ( item
) {
8366 * Select options by reference. Options not mentioned in the `items` array will be deselected.
8368 * @param {OO.ui.MultioptionWidget[]} items Items to select
8371 OO
.ui
.MultiselectWidget
.prototype.selectItems = function ( items
) {
8372 this.items
.forEach( function ( item
) {
8373 var selected
= items
.indexOf( item
) !== -1;
8374 item
.setSelected( selected
);
8380 * Select items by their data. Options not mentioned in the `datas` array will be deselected.
8382 * @param {Object[]|string[]} datas Values of items to select
8385 OO
.ui
.MultiselectWidget
.prototype.selectItemsByData = function ( datas
) {
8388 items
= datas
.map( function ( data
) {
8389 return widget
.findItemFromData( data
);
8391 this.selectItems( items
);
8396 * CheckboxMultioptionWidget is an option widget that looks like a checkbox.
8397 * The class is used with OO.ui.CheckboxMultiselectWidget to create a selection of checkbox options.
8398 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
8400 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Button_selects_and_option
8403 * @extends OO.ui.MultioptionWidget
8406 * @param {Object} [config] Configuration options
8408 OO
.ui
.CheckboxMultioptionWidget
= function OoUiCheckboxMultioptionWidget( config
) {
8409 // Configuration initialization
8410 config
= config
|| {};
8412 // Properties (must be done before parent constructor which calls #setDisabled)
8413 this.checkbox
= new OO
.ui
.CheckboxInputWidget();
8415 // Parent constructor
8416 OO
.ui
.CheckboxMultioptionWidget
.parent
.call( this, config
);
8419 this.checkbox
.on( 'change', this.onCheckboxChange
.bind( this ) );
8420 this.$element
.on( 'keydown', this.onKeyDown
.bind( this ) );
8424 .addClass( 'oo-ui-checkboxMultioptionWidget' )
8425 .prepend( this.checkbox
.$element
);
8430 OO
.inheritClass( OO
.ui
.CheckboxMultioptionWidget
, OO
.ui
.MultioptionWidget
);
8432 /* Static Properties */
8438 OO
.ui
.CheckboxMultioptionWidget
.static.tagName
= 'label';
8443 * Handle checkbox selected state change.
8447 OO
.ui
.CheckboxMultioptionWidget
.prototype.onCheckboxChange = function () {
8448 this.setSelected( this.checkbox
.isSelected() );
8454 OO
.ui
.CheckboxMultioptionWidget
.prototype.setSelected = function ( state
) {
8455 OO
.ui
.CheckboxMultioptionWidget
.parent
.prototype.setSelected
.call( this, state
);
8456 this.checkbox
.setSelected( state
);
8463 OO
.ui
.CheckboxMultioptionWidget
.prototype.setDisabled = function ( disabled
) {
8464 OO
.ui
.CheckboxMultioptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
8465 this.checkbox
.setDisabled( this.isDisabled() );
8472 OO
.ui
.CheckboxMultioptionWidget
.prototype.focus = function () {
8473 this.checkbox
.focus();
8477 * Handle key down events.
8480 * @param {jQuery.Event} e
8482 OO
.ui
.CheckboxMultioptionWidget
.prototype.onKeyDown = function ( e
) {
8484 element
= this.getElementGroup(),
8487 if ( e
.keyCode
=== OO
.ui
.Keys
.LEFT
|| e
.keyCode
=== OO
.ui
.Keys
.UP
) {
8488 nextItem
= element
.getRelativeFocusableItem( this, -1 );
8489 } else if ( e
.keyCode
=== OO
.ui
.Keys
.RIGHT
|| e
.keyCode
=== OO
.ui
.Keys
.DOWN
) {
8490 nextItem
= element
.getRelativeFocusableItem( this, 1 );
8500 * CheckboxMultiselectWidget is a {@link OO.ui.MultiselectWidget multiselect widget} that contains
8501 * checkboxes and is used together with OO.ui.CheckboxMultioptionWidget. The
8502 * CheckboxMultiselectWidget provides an interface for adding, removing and selecting options.
8503 * Please see the [OOUI documentation on MediaWiki][1] for more information.
8505 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
8506 * OO.ui.CheckboxMultiselectInputWidget instead.
8509 * // A CheckboxMultiselectWidget with CheckboxMultioptions.
8510 * var option1 = new OO.ui.CheckboxMultioptionWidget( {
8513 * label: 'Selected checkbox'
8516 * var option2 = new OO.ui.CheckboxMultioptionWidget( {
8518 * label: 'Unselected checkbox'
8521 * var multiselect=new OO.ui.CheckboxMultiselectWidget( {
8522 * items: [ option1, option2 ]
8525 * $( 'body' ).append( multiselect.$element );
8527 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
8530 * @extends OO.ui.MultiselectWidget
8533 * @param {Object} [config] Configuration options
8535 OO
.ui
.CheckboxMultiselectWidget
= function OoUiCheckboxMultiselectWidget( config
) {
8536 // Parent constructor
8537 OO
.ui
.CheckboxMultiselectWidget
.parent
.call( this, config
);
8540 this.$lastClicked
= null;
8543 this.$group
.on( 'click', this.onClick
.bind( this ) );
8547 .addClass( 'oo-ui-checkboxMultiselectWidget' );
8552 OO
.inheritClass( OO
.ui
.CheckboxMultiselectWidget
, OO
.ui
.MultiselectWidget
);
8557 * Get an option by its position relative to the specified item (or to the start of the option array,
8558 * if item is `null`). The direction in which to search through the option array is specified with a
8559 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
8560 * `null` if there are no options in the array.
8562 * @param {OO.ui.CheckboxMultioptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
8563 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
8564 * @return {OO.ui.CheckboxMultioptionWidget|null} Item at position, `null` if there are no items in the select
8566 OO
.ui
.CheckboxMultiselectWidget
.prototype.getRelativeFocusableItem = function ( item
, direction
) {
8567 var currentIndex
, nextIndex
, i
,
8568 increase
= direction
> 0 ? 1 : -1,
8569 len
= this.items
.length
;
8572 currentIndex
= this.items
.indexOf( item
);
8573 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
8575 // If no item is selected and moving forward, start at the beginning.
8576 // If moving backward, start at the end.
8577 nextIndex
= direction
> 0 ? 0 : len
- 1;
8580 for ( i
= 0; i
< len
; i
++ ) {
8581 item
= this.items
[ nextIndex
];
8582 if ( item
&& !item
.isDisabled() ) {
8585 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
8591 * Handle click events on checkboxes.
8593 * @param {jQuery.Event} e
8595 OO
.ui
.CheckboxMultiselectWidget
.prototype.onClick = function ( e
) {
8596 var $options
, lastClickedIndex
, nowClickedIndex
, i
, direction
, wasSelected
, items
,
8597 $lastClicked
= this.$lastClicked
,
8598 $nowClicked
= $( e
.target
).closest( '.oo-ui-checkboxMultioptionWidget' )
8599 .not( '.oo-ui-widget-disabled' );
8601 // Allow selecting multiple options at once by Shift-clicking them
8602 if ( $lastClicked
&& $nowClicked
.length
&& e
.shiftKey
) {
8603 $options
= this.$group
.find( '.oo-ui-checkboxMultioptionWidget' );
8604 lastClickedIndex
= $options
.index( $lastClicked
);
8605 nowClickedIndex
= $options
.index( $nowClicked
);
8606 // If it's the same item, either the user is being silly, or it's a fake event generated by the
8607 // browser. In either case we don't need custom handling.
8608 if ( nowClickedIndex
!== lastClickedIndex
) {
8610 wasSelected
= items
[ nowClickedIndex
].isSelected();
8611 direction
= nowClickedIndex
> lastClickedIndex
? 1 : -1;
8613 // This depends on the DOM order of the items and the order of the .items array being the same.
8614 for ( i
= lastClickedIndex
; i
!== nowClickedIndex
; i
+= direction
) {
8615 if ( !items
[ i
].isDisabled() ) {
8616 items
[ i
].setSelected( !wasSelected
);
8619 // For the now-clicked element, use immediate timeout to allow the browser to do its own
8620 // handling first, then set our value. The order in which events happen is different for
8621 // clicks on the <input> and on the <label> and there are additional fake clicks fired for
8622 // non-click actions that change the checkboxes.
8624 setTimeout( function () {
8625 if ( !items
[ nowClickedIndex
].isDisabled() ) {
8626 items
[ nowClickedIndex
].setSelected( !wasSelected
);
8632 if ( $nowClicked
.length
) {
8633 this.$lastClicked
= $nowClicked
;
8642 OO
.ui
.CheckboxMultiselectWidget
.prototype.focus = function () {
8644 if ( !this.isDisabled() ) {
8645 item
= this.getRelativeFocusableItem( null, 1 );
8656 OO
.ui
.CheckboxMultiselectWidget
.prototype.simulateLabelClick = function () {
8661 * Progress bars visually display the status of an operation, such as a download,
8662 * and can be either determinate or indeterminate:
8664 * - **determinate** process bars show the percent of an operation that is complete.
8666 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
8667 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
8668 * not use percentages.
8670 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
8673 * // Examples of determinate and indeterminate progress bars.
8674 * var progressBar1 = new OO.ui.ProgressBarWidget( {
8677 * var progressBar2 = new OO.ui.ProgressBarWidget();
8679 * // Create a FieldsetLayout to layout progress bars
8680 * var fieldset = new OO.ui.FieldsetLayout;
8681 * fieldset.addItems( [
8682 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
8683 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
8685 * $( 'body' ).append( fieldset.$element );
8688 * @extends OO.ui.Widget
8691 * @param {Object} [config] Configuration options
8692 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
8693 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
8694 * By default, the progress bar is indeterminate.
8696 OO
.ui
.ProgressBarWidget
= function OoUiProgressBarWidget( config
) {
8697 // Configuration initialization
8698 config
= config
|| {};
8700 // Parent constructor
8701 OO
.ui
.ProgressBarWidget
.parent
.call( this, config
);
8704 this.$bar
= $( '<div>' );
8705 this.progress
= null;
8708 this.setProgress( config
.progress
!== undefined ? config
.progress
: false );
8709 this.$bar
.addClass( 'oo-ui-progressBarWidget-bar' );
8712 role
: 'progressbar',
8714 'aria-valuemax': 100
8716 .addClass( 'oo-ui-progressBarWidget' )
8717 .append( this.$bar
);
8722 OO
.inheritClass( OO
.ui
.ProgressBarWidget
, OO
.ui
.Widget
);
8724 /* Static Properties */
8730 OO
.ui
.ProgressBarWidget
.static.tagName
= 'div';
8735 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
8737 * @return {number|boolean} Progress percent
8739 OO
.ui
.ProgressBarWidget
.prototype.getProgress = function () {
8740 return this.progress
;
8744 * Set the percent of the process completed or `false` for an indeterminate process.
8746 * @param {number|boolean} progress Progress percent or `false` for indeterminate
8748 OO
.ui
.ProgressBarWidget
.prototype.setProgress = function ( progress
) {
8749 this.progress
= progress
;
8751 if ( progress
!== false ) {
8752 this.$bar
.css( 'width', this.progress
+ '%' );
8753 this.$element
.attr( 'aria-valuenow', this.progress
);
8755 this.$bar
.css( 'width', '' );
8756 this.$element
.removeAttr( 'aria-valuenow' );
8758 this.$element
.toggleClass( 'oo-ui-progressBarWidget-indeterminate', progress
=== false );
8762 * InputWidget is the base class for all input widgets, which
8763 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
8764 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
8765 * See the [OOUI documentation on MediaWiki] [1] for more information and examples.
8767 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
8771 * @extends OO.ui.Widget
8772 * @mixins OO.ui.mixin.FlaggedElement
8773 * @mixins OO.ui.mixin.TabIndexedElement
8774 * @mixins OO.ui.mixin.TitledElement
8775 * @mixins OO.ui.mixin.AccessKeyedElement
8778 * @param {Object} [config] Configuration options
8779 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
8780 * @cfg {string} [value=''] The value of the input.
8781 * @cfg {string} [dir] The directionality of the input (ltr/rtl).
8782 * @cfg {string} [inputId] The value of the input’s HTML `id` attribute.
8783 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
8784 * before it is accepted.
8786 OO
.ui
.InputWidget
= function OoUiInputWidget( config
) {
8787 // Configuration initialization
8788 config
= config
|| {};
8790 // Parent constructor
8791 OO
.ui
.InputWidget
.parent
.call( this, config
);
8794 // See #reusePreInfuseDOM about config.$input
8795 this.$input
= config
.$input
|| this.getInputElement( config
);
8797 this.inputFilter
= config
.inputFilter
;
8799 // Mixin constructors
8800 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
8801 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
8802 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
8803 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$input
} ) );
8806 this.$input
.on( 'keydown mouseup cut paste change input select', this.onEdit
.bind( this ) );
8810 .addClass( 'oo-ui-inputWidget-input' )
8811 .attr( 'name', config
.name
)
8812 .prop( 'disabled', this.isDisabled() );
8814 .addClass( 'oo-ui-inputWidget' )
8815 .append( this.$input
);
8816 this.setValue( config
.value
);
8818 this.setDir( config
.dir
);
8820 if ( config
.inputId
!== undefined ) {
8821 this.setInputId( config
.inputId
);
8827 OO
.inheritClass( OO
.ui
.InputWidget
, OO
.ui
.Widget
);
8828 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.FlaggedElement
);
8829 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TabIndexedElement
);
8830 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TitledElement
);
8831 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
8833 /* Static Methods */
8838 OO
.ui
.InputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
8839 config
= OO
.ui
.InputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
8840 // Reusing `$input` lets browsers preserve inputted values across page reloads, see T114134.
8841 config
.$input
= $( node
).find( '.oo-ui-inputWidget-input' );
8848 OO
.ui
.InputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
8849 var state
= OO
.ui
.InputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
8850 if ( config
.$input
&& config
.$input
.length
) {
8851 state
.value
= config
.$input
.val();
8852 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
8853 state
.focus
= config
.$input
.is( ':focus' );
8863 * A change event is emitted when the value of the input changes.
8865 * @param {string} value
8871 * Get input element.
8873 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
8874 * different circumstances. The element must have a `value` property (like form elements).
8877 * @param {Object} config Configuration options
8878 * @return {jQuery} Input element
8880 OO
.ui
.InputWidget
.prototype.getInputElement = function () {
8881 return $( '<input>' );
8885 * Handle potentially value-changing events.
8888 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
8890 OO
.ui
.InputWidget
.prototype.onEdit = function () {
8892 if ( !this.isDisabled() ) {
8893 // Allow the stack to clear so the value will be updated
8894 setTimeout( function () {
8895 widget
.setValue( widget
.$input
.val() );
8901 * Get the value of the input.
8903 * @return {string} Input value
8905 OO
.ui
.InputWidget
.prototype.getValue = function () {
8906 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
8907 // it, and we won't know unless they're kind enough to trigger a 'change' event.
8908 var value
= this.$input
.val();
8909 if ( this.value
!== value
) {
8910 this.setValue( value
);
8916 * Set the directionality of the input.
8918 * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
8921 OO
.ui
.InputWidget
.prototype.setDir = function ( dir
) {
8922 this.$input
.prop( 'dir', dir
);
8927 * Set the value of the input.
8929 * @param {string} value New value
8933 OO
.ui
.InputWidget
.prototype.setValue = function ( value
) {
8934 value
= this.cleanUpValue( value
);
8935 // Update the DOM if it has changed. Note that with cleanUpValue, it
8936 // is possible for the DOM value to change without this.value changing.
8937 if ( this.$input
.val() !== value
) {
8938 this.$input
.val( value
);
8940 if ( this.value
!== value
) {
8942 this.emit( 'change', this.value
);
8944 // The first time that the value is set (probably while constructing the widget),
8945 // remember it in defaultValue. This property can be later used to check whether
8946 // the value of the input has been changed since it was created.
8947 if ( this.defaultValue
=== undefined ) {
8948 this.defaultValue
= this.value
;
8949 this.$input
[ 0 ].defaultValue
= this.defaultValue
;
8955 * Clean up incoming value.
8957 * Ensures value is a string, and converts undefined and null to empty string.
8960 * @param {string} value Original value
8961 * @return {string} Cleaned up value
8963 OO
.ui
.InputWidget
.prototype.cleanUpValue = function ( value
) {
8964 if ( value
=== undefined || value
=== null ) {
8966 } else if ( this.inputFilter
) {
8967 return this.inputFilter( String( value
) );
8969 return String( value
);
8976 OO
.ui
.InputWidget
.prototype.setDisabled = function ( state
) {
8977 OO
.ui
.InputWidget
.parent
.prototype.setDisabled
.call( this, state
);
8978 if ( this.$input
) {
8979 this.$input
.prop( 'disabled', this.isDisabled() );
8985 * Set the 'id' attribute of the `<input>` element.
8987 * @param {string} id
8990 OO
.ui
.InputWidget
.prototype.setInputId = function ( id
) {
8991 this.$input
.attr( 'id', id
);
8998 OO
.ui
.InputWidget
.prototype.restorePreInfuseState = function ( state
) {
8999 OO
.ui
.InputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
9000 if ( state
.value
!== undefined && state
.value
!== this.getValue() ) {
9001 this.setValue( state
.value
);
9003 if ( state
.focus
) {
9009 * Data widget intended for creating 'hidden'-type inputs.
9012 * @extends OO.ui.Widget
9015 * @param {Object} [config] Configuration options
9016 * @cfg {string} [value=''] The value of the input.
9017 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
9019 OO
.ui
.HiddenInputWidget
= function OoUiHiddenInputWidget( config
) {
9020 // Configuration initialization
9021 config
= $.extend( { value
: '', name
: '' }, config
);
9023 // Parent constructor
9024 OO
.ui
.HiddenInputWidget
.parent
.call( this, config
);
9027 this.$element
.attr( {
9029 value
: config
.value
,
9032 this.$element
.removeAttr( 'aria-disabled' );
9037 OO
.inheritClass( OO
.ui
.HiddenInputWidget
, OO
.ui
.Widget
);
9039 /* Static Properties */
9045 OO
.ui
.HiddenInputWidget
.static.tagName
= 'input';
9048 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
9049 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
9050 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
9051 * HTML `<button>` (the default) or an HTML `<input>` tags. See the
9052 * [OOUI documentation on MediaWiki] [1] for more information.
9055 * // A ButtonInputWidget rendered as an HTML button, the default.
9056 * var button = new OO.ui.ButtonInputWidget( {
9057 * label: 'Input button',
9061 * $( 'body' ).append( button.$element );
9063 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs#Button_inputs
9066 * @extends OO.ui.InputWidget
9067 * @mixins OO.ui.mixin.ButtonElement
9068 * @mixins OO.ui.mixin.IconElement
9069 * @mixins OO.ui.mixin.IndicatorElement
9070 * @mixins OO.ui.mixin.LabelElement
9071 * @mixins OO.ui.mixin.TitledElement
9074 * @param {Object} [config] Configuration options
9075 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
9076 * @cfg {boolean} [useInputTag=false] Use an `<input>` tag instead of a `<button>` tag, the default.
9077 * Widgets configured to be an `<input>` do not support {@link #icon icons} and {@link #indicator indicators},
9078 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
9079 * be set to `true` when there’s need to support IE 6 in a form with multiple buttons.
9081 OO
.ui
.ButtonInputWidget
= function OoUiButtonInputWidget( config
) {
9082 // Configuration initialization
9083 config
= $.extend( { type
: 'button', useInputTag
: false }, config
);
9085 // See InputWidget#reusePreInfuseDOM about config.$input
9086 if ( config
.$input
) {
9087 config
.$input
.empty();
9090 // Properties (must be set before parent constructor, which calls #setValue)
9091 this.useInputTag
= config
.useInputTag
;
9093 // Parent constructor
9094 OO
.ui
.ButtonInputWidget
.parent
.call( this, config
);
9096 // Mixin constructors
9097 OO
.ui
.mixin
.ButtonElement
.call( this, $.extend( {}, config
, { $button
: this.$input
} ) );
9098 OO
.ui
.mixin
.IconElement
.call( this, config
);
9099 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
9100 OO
.ui
.mixin
.LabelElement
.call( this, config
);
9101 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
9104 if ( !config
.useInputTag
) {
9105 this.$input
.append( this.$icon
, this.$label
, this.$indicator
);
9107 this.$element
.addClass( 'oo-ui-buttonInputWidget' );
9112 OO
.inheritClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.InputWidget
);
9113 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.ButtonElement
);
9114 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IconElement
);
9115 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
9116 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.LabelElement
);
9117 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.TitledElement
);
9119 /* Static Properties */
9125 OO
.ui
.ButtonInputWidget
.static.tagName
= 'span';
9133 OO
.ui
.ButtonInputWidget
.prototype.getInputElement = function ( config
) {
9135 type
= [ 'button', 'submit', 'reset' ].indexOf( config
.type
) !== -1 ? config
.type
: 'button';
9136 return $( '<' + ( config
.useInputTag
? 'input' : 'button' ) + ' type="' + type
+ '">' );
9142 * If #useInputTag is `true`, the label is set as the `value` of the `<input>` tag.
9144 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
9145 * text, or `null` for no label
9148 OO
.ui
.ButtonInputWidget
.prototype.setLabel = function ( label
) {
9149 if ( typeof label
=== 'function' ) {
9150 label
= OO
.ui
.resolveMsg( label
);
9153 if ( this.useInputTag
) {
9154 // Discard non-plaintext labels
9155 if ( typeof label
!== 'string' ) {
9159 this.$input
.val( label
);
9162 return OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.call( this, label
);
9166 * Set the value of the input.
9168 * This method is disabled for button inputs configured as {@link #useInputTag <input> tags}, as
9169 * they do not support {@link #value values}.
9171 * @param {string} value New value
9174 OO
.ui
.ButtonInputWidget
.prototype.setValue = function ( value
) {
9175 if ( !this.useInputTag
) {
9176 OO
.ui
.ButtonInputWidget
.parent
.prototype.setValue
.call( this, value
);
9184 OO
.ui
.ButtonInputWidget
.prototype.getInputId = function () {
9185 // Disable generating `<label>` elements for buttons. One would very rarely need additional label
9186 // for a button, and it's already a big clickable target, and it causes unexpected rendering.
9191 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
9192 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
9193 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
9194 * alignment. For more information, please see the [OOUI documentation on MediaWiki][1].
9196 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9199 * // An example of selected, unselected, and disabled checkbox inputs
9200 * var checkbox1=new OO.ui.CheckboxInputWidget( {
9204 * var checkbox2=new OO.ui.CheckboxInputWidget( {
9207 * var checkbox3=new OO.ui.CheckboxInputWidget( {
9211 * // Create a fieldset layout with fields for each checkbox.
9212 * var fieldset = new OO.ui.FieldsetLayout( {
9213 * label: 'Checkboxes'
9215 * fieldset.addItems( [
9216 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
9217 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
9218 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
9220 * $( 'body' ).append( fieldset.$element );
9222 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9225 * @extends OO.ui.InputWidget
9228 * @param {Object} [config] Configuration options
9229 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
9231 OO
.ui
.CheckboxInputWidget
= function OoUiCheckboxInputWidget( config
) {
9232 // Configuration initialization
9233 config
= config
|| {};
9235 // Parent constructor
9236 OO
.ui
.CheckboxInputWidget
.parent
.call( this, config
);
9239 this.checkIcon
= new OO
.ui
.IconWidget( {
9241 classes
: [ 'oo-ui-checkboxInputWidget-checkIcon' ]
9246 .addClass( 'oo-ui-checkboxInputWidget' )
9247 // Required for pretty styling in WikimediaUI theme
9248 .append( this.checkIcon
.$element
);
9249 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
9254 OO
.inheritClass( OO
.ui
.CheckboxInputWidget
, OO
.ui
.InputWidget
);
9256 /* Static Properties */
9262 OO
.ui
.CheckboxInputWidget
.static.tagName
= 'span';
9264 /* Static Methods */
9269 OO
.ui
.CheckboxInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9270 var state
= OO
.ui
.CheckboxInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9271 state
.checked
= config
.$input
.prop( 'checked' );
9281 OO
.ui
.CheckboxInputWidget
.prototype.getInputElement = function () {
9282 return $( '<input>' ).attr( 'type', 'checkbox' );
9288 OO
.ui
.CheckboxInputWidget
.prototype.onEdit = function () {
9290 if ( !this.isDisabled() ) {
9291 // Allow the stack to clear so the value will be updated
9292 setTimeout( function () {
9293 widget
.setSelected( widget
.$input
.prop( 'checked' ) );
9299 * Set selection state of this checkbox.
9301 * @param {boolean} state `true` for selected
9304 OO
.ui
.CheckboxInputWidget
.prototype.setSelected = function ( state
) {
9306 if ( this.selected
!== state
) {
9307 this.selected
= state
;
9308 this.$input
.prop( 'checked', this.selected
);
9309 this.emit( 'change', this.selected
);
9311 // The first time that the selection state is set (probably while constructing the widget),
9312 // remember it in defaultSelected. This property can be later used to check whether
9313 // the selection state of the input has been changed since it was created.
9314 if ( this.defaultSelected
=== undefined ) {
9315 this.defaultSelected
= this.selected
;
9316 this.$input
[ 0 ].defaultChecked
= this.defaultSelected
;
9322 * Check if this checkbox is selected.
9324 * @return {boolean} Checkbox is selected
9326 OO
.ui
.CheckboxInputWidget
.prototype.isSelected = function () {
9327 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
9328 // it, and we won't know unless they're kind enough to trigger a 'change' event.
9329 var selected
= this.$input
.prop( 'checked' );
9330 if ( this.selected
!== selected
) {
9331 this.setSelected( selected
);
9333 return this.selected
;
9339 OO
.ui
.CheckboxInputWidget
.prototype.simulateLabelClick = function () {
9340 if ( !this.isDisabled() ) {
9341 this.$input
.click();
9349 OO
.ui
.CheckboxInputWidget
.prototype.restorePreInfuseState = function ( state
) {
9350 OO
.ui
.CheckboxInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
9351 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
9352 this.setSelected( state
.checked
);
9357 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
9358 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
9359 * of a hidden HTML `input` tag. Please see the [OOUI documentation on MediaWiki][1] for
9360 * more information about input widgets.
9362 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
9363 * are no options. If no `value` configuration option is provided, the first option is selected.
9364 * If you need a state representing no value (no option being selected), use a DropdownWidget.
9366 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
9369 * // Example: A DropdownInputWidget with three options
9370 * var dropdownInput = new OO.ui.DropdownInputWidget( {
9372 * { data: 'a', label: 'First' },
9373 * { data: 'b', label: 'Second'},
9374 * { data: 'c', label: 'Third' }
9377 * $( 'body' ).append( dropdownInput.$element );
9379 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9382 * @extends OO.ui.InputWidget
9385 * @param {Object} [config] Configuration options
9386 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
9387 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
9388 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
9389 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
9390 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
9391 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
9393 OO
.ui
.DropdownInputWidget
= function OoUiDropdownInputWidget( config
) {
9394 // Configuration initialization
9395 config
= config
|| {};
9397 // Properties (must be done before parent constructor which calls #setDisabled)
9398 this.dropdownWidget
= new OO
.ui
.DropdownWidget( $.extend(
9400 $overlay
: config
.$overlay
9404 // Set up the options before parent constructor, which uses them to validate config.value.
9405 // Use this instead of setOptions() because this.$input is not set up yet.
9406 this.setOptionsData( config
.options
|| [] );
9408 // Parent constructor
9409 OO
.ui
.DropdownInputWidget
.parent
.call( this, config
);
9412 this.dropdownWidget
.getMenu().connect( this, { select
: 'onMenuSelect' } );
9416 .addClass( 'oo-ui-dropdownInputWidget' )
9417 .append( this.dropdownWidget
.$element
);
9418 this.setTabIndexedElement( this.dropdownWidget
.$tabIndexed
);
9423 OO
.inheritClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.InputWidget
);
9431 OO
.ui
.DropdownInputWidget
.prototype.getInputElement = function () {
9432 return $( '<select>' );
9436 * Handles menu select events.
9439 * @param {OO.ui.MenuOptionWidget|null} item Selected menu item
9441 OO
.ui
.DropdownInputWidget
.prototype.onMenuSelect = function ( item
) {
9442 this.setValue( item
? item
.getData() : '' );
9448 OO
.ui
.DropdownInputWidget
.prototype.setValue = function ( value
) {
9450 value
= this.cleanUpValue( value
);
9451 // Only allow setting values that are actually present in the dropdown
9452 selected
= this.dropdownWidget
.getMenu().findItemFromData( value
) ||
9453 this.dropdownWidget
.getMenu().findFirstSelectableItem();
9454 this.dropdownWidget
.getMenu().selectItem( selected
);
9455 value
= selected
? selected
.getData() : '';
9456 OO
.ui
.DropdownInputWidget
.parent
.prototype.setValue
.call( this, value
);
9457 if ( this.optionsDirty
) {
9458 // We reached this from the constructor or from #setOptions.
9459 // We have to update the <select> element.
9460 this.updateOptionsInterface();
9468 OO
.ui
.DropdownInputWidget
.prototype.setDisabled = function ( state
) {
9469 this.dropdownWidget
.setDisabled( state
);
9470 OO
.ui
.DropdownInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
9475 * Set the options available for this input.
9477 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9480 OO
.ui
.DropdownInputWidget
.prototype.setOptions = function ( options
) {
9481 var value
= this.getValue();
9483 this.setOptionsData( options
);
9485 // Re-set the value to update the visible interface (DropdownWidget and <select>).
9486 // In case the previous value is no longer an available option, select the first valid one.
9487 this.setValue( value
);
9493 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
9495 * This method may be called before the parent constructor, so various properties may not be
9498 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9501 OO
.ui
.DropdownInputWidget
.prototype.setOptionsData = function ( options
) {
9506 this.optionsDirty
= true;
9508 optionWidgets
= options
.map( function ( opt
) {
9511 if ( opt
.optgroup
!== undefined ) {
9512 return widget
.createMenuSectionOptionWidget( opt
.optgroup
);
9515 optValue
= widget
.cleanUpValue( opt
.data
);
9516 return widget
.createMenuOptionWidget(
9518 opt
.label
!== undefined ? opt
.label
: optValue
9523 this.dropdownWidget
.getMenu().clearItems().addItems( optionWidgets
);
9527 * Create a menu option widget.
9530 * @param {string} data Item data
9531 * @param {string} label Item label
9532 * @return {OO.ui.MenuOptionWidget} Option widget
9534 OO
.ui
.DropdownInputWidget
.prototype.createMenuOptionWidget = function ( data
, label
) {
9535 return new OO
.ui
.MenuOptionWidget( {
9542 * Create a menu section option widget.
9545 * @param {string} label Section item label
9546 * @return {OO.ui.MenuSectionOptionWidget} Menu section option widget
9548 OO
.ui
.DropdownInputWidget
.prototype.createMenuSectionOptionWidget = function ( label
) {
9549 return new OO
.ui
.MenuSectionOptionWidget( {
9555 * Update the user-visible interface to match the internal list of options and value.
9557 * This method must only be called after the parent constructor.
9561 OO
.ui
.DropdownInputWidget
.prototype.updateOptionsInterface = function () {
9563 $optionsContainer
= this.$input
,
9564 defaultValue
= this.defaultValue
,
9567 this.$input
.empty();
9569 this.dropdownWidget
.getMenu().getItems().forEach( function ( optionWidget
) {
9572 if ( !( optionWidget
instanceof OO
.ui
.MenuSectionOptionWidget
) ) {
9573 $optionNode
= $( '<option>' )
9574 .attr( 'value', optionWidget
.getData() )
9575 .text( optionWidget
.getLabel() );
9577 // Remember original selection state. This property can be later used to check whether
9578 // the selection state of the input has been changed since it was created.
9579 $optionNode
[ 0 ].defaultSelected
= ( optionWidget
.getData() === defaultValue
);
9581 $optionsContainer
.append( $optionNode
);
9583 $optionNode
= $( '<optgroup>' )
9584 .attr( 'label', optionWidget
.getLabel() );
9585 widget
.$input
.append( $optionNode
);
9586 $optionsContainer
= $optionNode
;
9590 this.optionsDirty
= false;
9596 OO
.ui
.DropdownInputWidget
.prototype.focus = function () {
9597 this.dropdownWidget
.focus();
9604 OO
.ui
.DropdownInputWidget
.prototype.blur = function () {
9605 this.dropdownWidget
.blur();
9610 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
9611 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
9612 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
9613 * please see the [OOUI documentation on MediaWiki][1].
9615 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9618 * // An example of selected, unselected, and disabled radio inputs
9619 * var radio1 = new OO.ui.RadioInputWidget( {
9623 * var radio2 = new OO.ui.RadioInputWidget( {
9626 * var radio3 = new OO.ui.RadioInputWidget( {
9630 * // Create a fieldset layout with fields for each radio button.
9631 * var fieldset = new OO.ui.FieldsetLayout( {
9632 * label: 'Radio inputs'
9634 * fieldset.addItems( [
9635 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
9636 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
9637 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
9639 * $( 'body' ).append( fieldset.$element );
9641 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9644 * @extends OO.ui.InputWidget
9647 * @param {Object} [config] Configuration options
9648 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
9650 OO
.ui
.RadioInputWidget
= function OoUiRadioInputWidget( config
) {
9651 // Configuration initialization
9652 config
= config
|| {};
9654 // Parent constructor
9655 OO
.ui
.RadioInputWidget
.parent
.call( this, config
);
9659 .addClass( 'oo-ui-radioInputWidget' )
9660 // Required for pretty styling in WikimediaUI theme
9661 .append( $( '<span>' ) );
9662 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
9667 OO
.inheritClass( OO
.ui
.RadioInputWidget
, OO
.ui
.InputWidget
);
9669 /* Static Properties */
9675 OO
.ui
.RadioInputWidget
.static.tagName
= 'span';
9677 /* Static Methods */
9682 OO
.ui
.RadioInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9683 var state
= OO
.ui
.RadioInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9684 state
.checked
= config
.$input
.prop( 'checked' );
9694 OO
.ui
.RadioInputWidget
.prototype.getInputElement = function () {
9695 return $( '<input>' ).attr( 'type', 'radio' );
9701 OO
.ui
.RadioInputWidget
.prototype.onEdit = function () {
9702 // RadioInputWidget doesn't track its state.
9706 * Set selection state of this radio button.
9708 * @param {boolean} state `true` for selected
9711 OO
.ui
.RadioInputWidget
.prototype.setSelected = function ( state
) {
9712 // RadioInputWidget doesn't track its state.
9713 this.$input
.prop( 'checked', state
);
9714 // The first time that the selection state is set (probably while constructing the widget),
9715 // remember it in defaultSelected. This property can be later used to check whether
9716 // the selection state of the input has been changed since it was created.
9717 if ( this.defaultSelected
=== undefined ) {
9718 this.defaultSelected
= state
;
9719 this.$input
[ 0 ].defaultChecked
= this.defaultSelected
;
9725 * Check if this radio button is selected.
9727 * @return {boolean} Radio is selected
9729 OO
.ui
.RadioInputWidget
.prototype.isSelected = function () {
9730 return this.$input
.prop( 'checked' );
9736 OO
.ui
.RadioInputWidget
.prototype.simulateLabelClick = function () {
9737 if ( !this.isDisabled() ) {
9738 this.$input
.click();
9746 OO
.ui
.RadioInputWidget
.prototype.restorePreInfuseState = function ( state
) {
9747 OO
.ui
.RadioInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
9748 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
9749 this.setSelected( state
.checked
);
9754 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
9755 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
9756 * of a hidden HTML `input` tag. Please see the [OOUI documentation on MediaWiki][1] for
9757 * more information about input widgets.
9759 * This and OO.ui.DropdownInputWidget support the same configuration options.
9762 * // Example: A RadioSelectInputWidget with three options
9763 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
9765 * { data: 'a', label: 'First' },
9766 * { data: 'b', label: 'Second'},
9767 * { data: 'c', label: 'Third' }
9770 * $( 'body' ).append( radioSelectInput.$element );
9772 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9775 * @extends OO.ui.InputWidget
9778 * @param {Object} [config] Configuration options
9779 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
9781 OO
.ui
.RadioSelectInputWidget
= function OoUiRadioSelectInputWidget( config
) {
9782 // Configuration initialization
9783 config
= config
|| {};
9785 // Properties (must be done before parent constructor which calls #setDisabled)
9786 this.radioSelectWidget
= new OO
.ui
.RadioSelectWidget();
9787 // Set up the options before parent constructor, which uses them to validate config.value.
9788 // Use this instead of setOptions() because this.$input is not set up yet
9789 this.setOptionsData( config
.options
|| [] );
9791 // Parent constructor
9792 OO
.ui
.RadioSelectInputWidget
.parent
.call( this, config
);
9795 this.radioSelectWidget
.connect( this, { select
: 'onMenuSelect' } );
9799 .addClass( 'oo-ui-radioSelectInputWidget' )
9800 .append( this.radioSelectWidget
.$element
);
9801 this.setTabIndexedElement( this.radioSelectWidget
.$tabIndexed
);
9806 OO
.inheritClass( OO
.ui
.RadioSelectInputWidget
, OO
.ui
.InputWidget
);
9808 /* Static Methods */
9813 OO
.ui
.RadioSelectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9814 var state
= OO
.ui
.RadioSelectInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9815 state
.value
= $( node
).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
9822 OO
.ui
.RadioSelectInputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
9823 config
= OO
.ui
.RadioSelectInputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
9824 // Cannot reuse the `<input type=radio>` set
9825 delete config
.$input
;
9835 OO
.ui
.RadioSelectInputWidget
.prototype.getInputElement = function () {
9836 // Use this instead of <input type="hidden">, because hidden inputs do not have separate
9837 // 'value' and 'defaultValue' properties, and InputWidget wants to handle 'defaultValue'.
9838 return $( '<input>' ).addClass( 'oo-ui-element-hidden' );
9842 * Handles menu select events.
9845 * @param {OO.ui.RadioOptionWidget} item Selected menu item
9847 OO
.ui
.RadioSelectInputWidget
.prototype.onMenuSelect = function ( item
) {
9848 this.setValue( item
.getData() );
9854 OO
.ui
.RadioSelectInputWidget
.prototype.setValue = function ( value
) {
9856 value
= this.cleanUpValue( value
);
9857 // Only allow setting values that are actually present in the dropdown
9858 selected
= this.radioSelectWidget
.findItemFromData( value
) ||
9859 this.radioSelectWidget
.findFirstSelectableItem();
9860 this.radioSelectWidget
.selectItem( selected
);
9861 value
= selected
? selected
.getData() : '';
9862 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setValue
.call( this, value
);
9869 OO
.ui
.RadioSelectInputWidget
.prototype.setDisabled = function ( state
) {
9870 this.radioSelectWidget
.setDisabled( state
);
9871 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
9876 * Set the options available for this input.
9878 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9881 OO
.ui
.RadioSelectInputWidget
.prototype.setOptions = function ( options
) {
9882 var value
= this.getValue();
9884 this.setOptionsData( options
);
9886 // Re-set the value to update the visible interface (RadioSelectWidget).
9887 // In case the previous value is no longer an available option, select the first valid one.
9888 this.setValue( value
);
9894 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
9896 * This method may be called before the parent constructor, so various properties may not be
9899 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9902 OO
.ui
.RadioSelectInputWidget
.prototype.setOptionsData = function ( options
) {
9905 this.radioSelectWidget
9907 .addItems( options
.map( function ( opt
) {
9908 var optValue
= widget
.cleanUpValue( opt
.data
);
9909 return new OO
.ui
.RadioOptionWidget( {
9911 label
: opt
.label
!== undefined ? opt
.label
: optValue
9919 OO
.ui
.RadioSelectInputWidget
.prototype.focus = function () {
9920 this.radioSelectWidget
.focus();
9927 OO
.ui
.RadioSelectInputWidget
.prototype.blur = function () {
9928 this.radioSelectWidget
.blur();
9933 * CheckboxMultiselectInputWidget is a
9934 * {@link OO.ui.CheckboxMultiselectWidget CheckboxMultiselectWidget} intended to be used within a
9935 * HTML form, such as a OO.ui.FormLayout. The selected values are synchronized with the value of
9936 * HTML `<input type=checkbox>` tags. Please see the [OOUI documentation on MediaWiki][1] for
9937 * more information about input widgets.
9940 * // Example: A CheckboxMultiselectInputWidget with three options
9941 * var multiselectInput = new OO.ui.CheckboxMultiselectInputWidget( {
9943 * { data: 'a', label: 'First' },
9944 * { data: 'b', label: 'Second'},
9945 * { data: 'c', label: 'Third' }
9948 * $( 'body' ).append( multiselectInput.$element );
9950 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9953 * @extends OO.ui.InputWidget
9956 * @param {Object} [config] Configuration options
9957 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: …, disabled: … }`
9959 OO
.ui
.CheckboxMultiselectInputWidget
= function OoUiCheckboxMultiselectInputWidget( config
) {
9960 // Configuration initialization
9961 config
= config
|| {};
9963 // Properties (must be done before parent constructor which calls #setDisabled)
9964 this.checkboxMultiselectWidget
= new OO
.ui
.CheckboxMultiselectWidget();
9965 // Must be set before the #setOptionsData call below
9966 this.inputName
= config
.name
;
9967 // Set up the options before parent constructor, which uses them to validate config.value.
9968 // Use this instead of setOptions() because this.$input is not set up yet
9969 this.setOptionsData( config
.options
|| [] );
9971 // Parent constructor
9972 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.call( this, config
);
9975 this.checkboxMultiselectWidget
.connect( this, { select
: 'onCheckboxesSelect' } );
9979 .addClass( 'oo-ui-checkboxMultiselectInputWidget' )
9980 .append( this.checkboxMultiselectWidget
.$element
);
9981 // We don't use this.$input, but rather the CheckboxInputWidgets inside each option
9982 this.$input
.detach();
9987 OO
.inheritClass( OO
.ui
.CheckboxMultiselectInputWidget
, OO
.ui
.InputWidget
);
9989 /* Static Methods */
9994 OO
.ui
.CheckboxMultiselectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9995 var state
= OO
.ui
.CheckboxMultiselectInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9996 state
.value
= $( node
).find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
9997 .toArray().map( function ( el
) { return el
.value
; } );
10004 OO
.ui
.CheckboxMultiselectInputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
10005 config
= OO
.ui
.CheckboxMultiselectInputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
10006 // Cannot reuse the `<input type=checkbox>` set
10007 delete config
.$input
;
10017 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.getInputElement = function () {
10019 return $( '<unused>' );
10023 * Handles CheckboxMultiselectWidget select events.
10027 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.onCheckboxesSelect = function () {
10028 this.setValue( this.checkboxMultiselectWidget
.findSelectedItemsData() );
10034 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.getValue = function () {
10035 var value
= this.$element
.find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
10036 .toArray().map( function ( el
) { return el
.value
; } );
10037 if ( this.value
!== value
) {
10038 this.setValue( value
);
10046 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setValue = function ( value
) {
10047 value
= this.cleanUpValue( value
);
10048 this.checkboxMultiselectWidget
.selectItemsByData( value
);
10049 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.setValue
.call( this, value
);
10050 if ( this.optionsDirty
) {
10051 // We reached this from the constructor or from #setOptions.
10052 // We have to update the <select> element.
10053 this.updateOptionsInterface();
10059 * Clean up incoming value.
10061 * @param {string[]} value Original value
10062 * @return {string[]} Cleaned up value
10064 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.cleanUpValue = function ( value
) {
10065 var i
, singleValue
,
10067 if ( !Array
.isArray( value
) ) {
10070 for ( i
= 0; i
< value
.length
; i
++ ) {
10072 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.cleanUpValue
.call( this, value
[ i
] );
10073 // Remove options that we don't have here
10074 if ( !this.checkboxMultiselectWidget
.findItemFromData( singleValue
) ) {
10077 cleanValue
.push( singleValue
);
10085 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setDisabled = function ( state
) {
10086 this.checkboxMultiselectWidget
.setDisabled( state
);
10087 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
10092 * Set the options available for this input.
10094 * @param {Object[]} options Array of menu options in the format `{ data: …, label: …, disabled: … }`
10097 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setOptions = function ( options
) {
10098 var value
= this.getValue();
10100 this.setOptionsData( options
);
10102 // Re-set the value to update the visible interface (CheckboxMultiselectWidget).
10103 // This will also get rid of any stale options that we just removed.
10104 this.setValue( value
);
10110 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
10112 * This method may be called before the parent constructor, so various properties may not be
10115 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
10118 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setOptionsData = function ( options
) {
10121 this.optionsDirty
= true;
10123 this.checkboxMultiselectWidget
10125 .addItems( options
.map( function ( opt
) {
10126 var optValue
, item
, optDisabled
;
10128 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.cleanUpValue
.call( widget
, opt
.data
);
10129 optDisabled
= opt
.disabled
!== undefined ? opt
.disabled
: false;
10130 item
= new OO
.ui
.CheckboxMultioptionWidget( {
10132 label
: opt
.label
!== undefined ? opt
.label
: optValue
,
10133 disabled
: optDisabled
10135 // Set the 'name' and 'value' for form submission
10136 item
.checkbox
.$input
.attr( 'name', widget
.inputName
);
10137 item
.checkbox
.setValue( optValue
);
10143 * Update the user-visible interface to match the internal list of options and value.
10145 * This method must only be called after the parent constructor.
10149 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.updateOptionsInterface = function () {
10150 var defaultValue
= this.defaultValue
;
10152 this.checkboxMultiselectWidget
.getItems().forEach( function ( item
) {
10153 // Remember original selection state. This property can be later used to check whether
10154 // the selection state of the input has been changed since it was created.
10155 var isDefault
= defaultValue
.indexOf( item
.getData() ) !== -1;
10156 item
.checkbox
.defaultSelected
= isDefault
;
10157 item
.checkbox
.$input
[ 0 ].defaultChecked
= isDefault
;
10160 this.optionsDirty
= false;
10166 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.focus = function () {
10167 this.checkboxMultiselectWidget
.focus();
10172 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
10173 * size of the field as well as its presentation. In addition, these widgets can be configured
10174 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
10175 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
10176 * which modifies incoming values rather than validating them.
10177 * Please see the [OOUI documentation on MediaWiki] [1] for more information and examples.
10179 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
10182 * // Example of a text input widget
10183 * var textInput = new OO.ui.TextInputWidget( {
10184 * value: 'Text input'
10186 * $( 'body' ).append( textInput.$element );
10188 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
10191 * @extends OO.ui.InputWidget
10192 * @mixins OO.ui.mixin.IconElement
10193 * @mixins OO.ui.mixin.IndicatorElement
10194 * @mixins OO.ui.mixin.PendingElement
10195 * @mixins OO.ui.mixin.LabelElement
10198 * @param {Object} [config] Configuration options
10199 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password'
10200 * 'email', 'url' or 'number'.
10201 * @cfg {string} [placeholder] Placeholder text
10202 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
10203 * instruct the browser to focus this widget.
10204 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
10205 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
10207 * For unfortunate historical reasons, this counts the number of UTF-16 code units rather than
10208 * Unicode codepoints, which means that codepoints outside the Basic Multilingual Plane (e.g.
10209 * many emojis) count as 2 characters each.
10210 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
10211 * the value or placeholder text: `'before'` or `'after'`
10212 * @cfg {boolean} [required=false] Mark the field as required with `true`. Implies `indicator: 'required'`.
10213 * Note that `false` & setting `indicator: 'required' will result in no indicator shown.
10214 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
10215 * @cfg {boolean} [spellcheck] Should the browser support spellcheck for this field (`undefined` means
10216 * leaving it up to the browser).
10217 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
10218 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
10219 * (the value must contain only numbers); when RegExp, a regular expression that must match the
10220 * value for it to be considered valid; when Function, a function receiving the value as parameter
10221 * that must return true, or promise resolving to true, for it to be considered valid.
10223 OO
.ui
.TextInputWidget
= function OoUiTextInputWidget( config
) {
10224 // Configuration initialization
10225 config
= $.extend( {
10227 labelPosition
: 'after'
10230 // Parent constructor
10231 OO
.ui
.TextInputWidget
.parent
.call( this, config
);
10233 // Mixin constructors
10234 OO
.ui
.mixin
.IconElement
.call( this, config
);
10235 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
10236 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$input
} ) );
10237 OO
.ui
.mixin
.LabelElement
.call( this, config
);
10240 this.type
= this.getSaneType( config
);
10241 this.readOnly
= false;
10242 this.required
= false;
10243 this.validate
= null;
10244 this.styleHeight
= null;
10245 this.scrollWidth
= null;
10247 this.setValidation( config
.validate
);
10248 this.setLabelPosition( config
.labelPosition
);
10252 keypress
: this.onKeyPress
.bind( this ),
10253 blur
: this.onBlur
.bind( this ),
10254 focus
: this.onFocus
.bind( this )
10256 this.$icon
.on( 'mousedown', this.onIconMouseDown
.bind( this ) );
10257 this.$indicator
.on( 'mousedown', this.onIndicatorMouseDown
.bind( this ) );
10258 this.on( 'labelChange', this.updatePosition
.bind( this ) );
10259 this.on( 'change', OO
.ui
.debounce( this.onDebouncedChange
.bind( this ), 250 ) );
10263 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type
)
10264 .append( this.$icon
, this.$indicator
);
10265 this.setReadOnly( !!config
.readOnly
);
10266 this.setRequired( !!config
.required
);
10267 if ( config
.placeholder
!== undefined ) {
10268 this.$input
.attr( 'placeholder', config
.placeholder
);
10270 if ( config
.maxLength
!== undefined ) {
10271 this.$input
.attr( 'maxlength', config
.maxLength
);
10273 if ( config
.autofocus
) {
10274 this.$input
.attr( 'autofocus', 'autofocus' );
10276 if ( config
.autocomplete
=== false ) {
10277 this.$input
.attr( 'autocomplete', 'off' );
10278 // Turning off autocompletion also disables "form caching" when the user navigates to a
10279 // different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI.
10281 beforeunload: function () {
10282 this.$input
.removeAttr( 'autocomplete' );
10284 pageshow: function () {
10285 // Browsers don't seem to actually fire this event on "Back", they instead just reload the
10286 // whole page... it shouldn't hurt, though.
10287 this.$input
.attr( 'autocomplete', 'off' );
10291 if ( config
.spellcheck
!== undefined ) {
10292 this.$input
.attr( 'spellcheck', config
.spellcheck
? 'true' : 'false' );
10294 if ( this.label
) {
10295 this.isWaitingToBeAttached
= true;
10296 this.installParentChangeDetector();
10302 OO
.inheritClass( OO
.ui
.TextInputWidget
, OO
.ui
.InputWidget
);
10303 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IconElement
);
10304 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
10305 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.PendingElement
);
10306 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.LabelElement
);
10308 /* Static Properties */
10310 OO
.ui
.TextInputWidget
.static.validationPatterns
= {
10318 * An `enter` event is emitted when the user presses 'enter' inside the text box.
10326 * Handle icon mouse down events.
10329 * @param {jQuery.Event} e Mouse down event
10331 OO
.ui
.TextInputWidget
.prototype.onIconMouseDown = function ( e
) {
10332 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
10339 * Handle indicator mouse down events.
10342 * @param {jQuery.Event} e Mouse down event
10344 OO
.ui
.TextInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
10345 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
10352 * Handle key press events.
10355 * @param {jQuery.Event} e Key press event
10356 * @fires enter If enter key is pressed
10358 OO
.ui
.TextInputWidget
.prototype.onKeyPress = function ( e
) {
10359 if ( e
.which
=== OO
.ui
.Keys
.ENTER
) {
10360 this.emit( 'enter', e
);
10365 * Handle blur events.
10368 * @param {jQuery.Event} e Blur event
10370 OO
.ui
.TextInputWidget
.prototype.onBlur = function () {
10371 this.setValidityFlag();
10375 * Handle focus events.
10378 * @param {jQuery.Event} e Focus event
10380 OO
.ui
.TextInputWidget
.prototype.onFocus = function () {
10381 if ( this.isWaitingToBeAttached
) {
10382 // If we've received focus, then we must be attached to the document, and if
10383 // isWaitingToBeAttached is still true, that means the handler never fired. Fire it now.
10384 this.onElementAttach();
10386 this.setValidityFlag( true );
10390 * Handle element attach events.
10393 * @param {jQuery.Event} e Element attach event
10395 OO
.ui
.TextInputWidget
.prototype.onElementAttach = function () {
10396 this.isWaitingToBeAttached
= false;
10397 // Any previously calculated size is now probably invalid if we reattached elsewhere
10398 this.valCache
= null;
10399 this.positionLabel();
10403 * Handle debounced change events.
10405 * @param {string} value
10408 OO
.ui
.TextInputWidget
.prototype.onDebouncedChange = function () {
10409 this.setValidityFlag();
10413 * Check if the input is {@link #readOnly read-only}.
10415 * @return {boolean}
10417 OO
.ui
.TextInputWidget
.prototype.isReadOnly = function () {
10418 return this.readOnly
;
10422 * Set the {@link #readOnly read-only} state of the input.
10424 * @param {boolean} state Make input read-only
10427 OO
.ui
.TextInputWidget
.prototype.setReadOnly = function ( state
) {
10428 this.readOnly
= !!state
;
10429 this.$input
.prop( 'readOnly', this.readOnly
);
10434 * Check if the input is {@link #required required}.
10436 * @return {boolean}
10438 OO
.ui
.TextInputWidget
.prototype.isRequired = function () {
10439 return this.required
;
10443 * Set the {@link #required required} state of the input.
10445 * @param {boolean} state Make input required
10448 OO
.ui
.TextInputWidget
.prototype.setRequired = function ( state
) {
10449 this.required
= !!state
;
10450 if ( this.required
) {
10452 .prop( 'required', true )
10453 .attr( 'aria-required', 'true' );
10454 if ( this.getIndicator() === null ) {
10455 this.setIndicator( 'required' );
10459 .prop( 'required', false )
10460 .removeAttr( 'aria-required' );
10461 if ( this.getIndicator() === 'required' ) {
10462 this.setIndicator( null );
10469 * Support function for making #onElementAttach work across browsers.
10471 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
10472 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
10474 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
10475 * first time that the element gets attached to the documented.
10477 OO
.ui
.TextInputWidget
.prototype.installParentChangeDetector = function () {
10478 var mutationObserver
, onRemove
, topmostNode
, fakeParentNode
,
10479 MutationObserver
= window
.MutationObserver
|| window
.WebKitMutationObserver
|| window
.MozMutationObserver
,
10482 if ( MutationObserver
) {
10483 // The new way. If only it wasn't so ugly.
10485 if ( this.isElementAttached() ) {
10486 // Widget is attached already, do nothing. This breaks the functionality of this function when
10487 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
10488 // would require observation of the whole document, which would hurt performance of other,
10489 // more important code.
10493 // Find topmost node in the tree
10494 topmostNode
= this.$element
[ 0 ];
10495 while ( topmostNode
.parentNode
) {
10496 topmostNode
= topmostNode
.parentNode
;
10499 // We have no way to detect the $element being attached somewhere without observing the entire
10500 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
10501 // parent node of $element, and instead detect when $element is removed from it (and thus
10502 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
10503 // doesn't get attached, we end up back here and create the parent.
10505 mutationObserver
= new MutationObserver( function ( mutations
) {
10506 var i
, j
, removedNodes
;
10507 for ( i
= 0; i
< mutations
.length
; i
++ ) {
10508 removedNodes
= mutations
[ i
].removedNodes
;
10509 for ( j
= 0; j
< removedNodes
.length
; j
++ ) {
10510 if ( removedNodes
[ j
] === topmostNode
) {
10511 setTimeout( onRemove
, 0 );
10518 onRemove = function () {
10519 // If the node was attached somewhere else, report it
10520 if ( widget
.isElementAttached() ) {
10521 widget
.onElementAttach();
10523 mutationObserver
.disconnect();
10524 widget
.installParentChangeDetector();
10527 // Create a fake parent and observe it
10528 fakeParentNode
= $( '<div>' ).append( topmostNode
)[ 0 ];
10529 mutationObserver
.observe( fakeParentNode
, { childList
: true } );
10531 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
10532 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
10533 this.$element
.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach
.bind( this ) );
10541 OO
.ui
.TextInputWidget
.prototype.getInputElement = function ( config
) {
10542 if ( this.getSaneType( config
) === 'number' ) {
10543 return $( '<input>' )
10544 .attr( 'step', 'any' )
10545 .attr( 'type', 'number' );
10547 return $( '<input>' ).attr( 'type', this.getSaneType( config
) );
10552 * Get sanitized value for 'type' for given config.
10554 * @param {Object} config Configuration options
10555 * @return {string|null}
10558 OO
.ui
.TextInputWidget
.prototype.getSaneType = function ( config
) {
10559 var allowedTypes
= [
10566 return allowedTypes
.indexOf( config
.type
) !== -1 ? config
.type
: 'text';
10570 * Focus the input and select a specified range within the text.
10572 * @param {number} from Select from offset
10573 * @param {number} [to] Select to offset, defaults to from
10576 OO
.ui
.TextInputWidget
.prototype.selectRange = function ( from, to
) {
10577 var isBackwards
, start
, end
,
10578 input
= this.$input
[ 0 ];
10582 isBackwards
= to
< from;
10583 start
= isBackwards
? to
: from;
10584 end
= isBackwards
? from : to
;
10589 input
.setSelectionRange( start
, end
, isBackwards
? 'backward' : 'forward' );
10591 // IE throws an exception if you call setSelectionRange on a unattached DOM node.
10592 // Rather than expensively check if the input is attached every time, just check
10593 // if it was the cause of an error being thrown. If not, rethrow the error.
10594 if ( this.getElementDocument().body
.contains( input
) ) {
10602 * Get an object describing the current selection range in a directional manner
10604 * @return {Object} Object containing 'from' and 'to' offsets
10606 OO
.ui
.TextInputWidget
.prototype.getRange = function () {
10607 var input
= this.$input
[ 0 ],
10608 start
= input
.selectionStart
,
10609 end
= input
.selectionEnd
,
10610 isBackwards
= input
.selectionDirection
=== 'backward';
10613 from: isBackwards
? end
: start
,
10614 to
: isBackwards
? start
: end
10619 * Get the length of the text input value.
10621 * This could differ from the length of #getValue if the
10622 * value gets filtered
10624 * @return {number} Input length
10626 OO
.ui
.TextInputWidget
.prototype.getInputLength = function () {
10627 return this.$input
[ 0 ].value
.length
;
10631 * Focus the input and select the entire text.
10635 OO
.ui
.TextInputWidget
.prototype.select = function () {
10636 return this.selectRange( 0, this.getInputLength() );
10640 * Focus the input and move the cursor to the start.
10644 OO
.ui
.TextInputWidget
.prototype.moveCursorToStart = function () {
10645 return this.selectRange( 0 );
10649 * Focus the input and move the cursor to the end.
10653 OO
.ui
.TextInputWidget
.prototype.moveCursorToEnd = function () {
10654 return this.selectRange( this.getInputLength() );
10658 * Insert new content into the input.
10660 * @param {string} content Content to be inserted
10663 OO
.ui
.TextInputWidget
.prototype.insertContent = function ( content
) {
10665 range
= this.getRange(),
10666 value
= this.getValue();
10668 start
= Math
.min( range
.from, range
.to
);
10669 end
= Math
.max( range
.from, range
.to
);
10671 this.setValue( value
.slice( 0, start
) + content
+ value
.slice( end
) );
10672 this.selectRange( start
+ content
.length
);
10677 * Insert new content either side of a selection.
10679 * @param {string} pre Content to be inserted before the selection
10680 * @param {string} post Content to be inserted after the selection
10683 OO
.ui
.TextInputWidget
.prototype.encapsulateContent = function ( pre
, post
) {
10685 range
= this.getRange(),
10686 offset
= pre
.length
;
10688 start
= Math
.min( range
.from, range
.to
);
10689 end
= Math
.max( range
.from, range
.to
);
10691 this.selectRange( start
).insertContent( pre
);
10692 this.selectRange( offset
+ end
).insertContent( post
);
10694 this.selectRange( offset
+ start
, offset
+ end
);
10699 * Set the validation pattern.
10701 * The validation pattern is either a regular expression, a function, or the symbolic name of a
10702 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
10703 * value must contain only numbers).
10705 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
10706 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
10708 OO
.ui
.TextInputWidget
.prototype.setValidation = function ( validate
) {
10709 if ( validate
instanceof RegExp
|| validate
instanceof Function
) {
10710 this.validate
= validate
;
10712 this.validate
= this.constructor.static.validationPatterns
[ validate
] || /.*/;
10717 * Sets the 'invalid' flag appropriately.
10719 * @param {boolean} [isValid] Optionally override validation result
10721 OO
.ui
.TextInputWidget
.prototype.setValidityFlag = function ( isValid
) {
10723 setFlag = function ( valid
) {
10725 widget
.$input
.attr( 'aria-invalid', 'true' );
10727 widget
.$input
.removeAttr( 'aria-invalid' );
10729 widget
.setFlags( { invalid
: !valid
} );
10732 if ( isValid
!== undefined ) {
10733 setFlag( isValid
);
10735 this.getValidity().then( function () {
10744 * Get the validity of current value.
10746 * This method returns a promise that resolves if the value is valid and rejects if
10747 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
10749 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
10751 OO
.ui
.TextInputWidget
.prototype.getValidity = function () {
10754 function rejectOrResolve( valid
) {
10756 return $.Deferred().resolve().promise();
10758 return $.Deferred().reject().promise();
10762 // Check browser validity and reject if it is invalid
10764 this.$input
[ 0 ].checkValidity
!== undefined &&
10765 this.$input
[ 0 ].checkValidity() === false
10767 return rejectOrResolve( false );
10770 // Run our checks if the browser thinks the field is valid
10771 if ( this.validate
instanceof Function
) {
10772 result
= this.validate( this.getValue() );
10773 if ( result
&& $.isFunction( result
.promise
) ) {
10774 return result
.promise().then( function ( valid
) {
10775 return rejectOrResolve( valid
);
10778 return rejectOrResolve( result
);
10781 return rejectOrResolve( this.getValue().match( this.validate
) );
10786 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
10788 * @param {string} labelPosition Label position, 'before' or 'after'
10791 OO
.ui
.TextInputWidget
.prototype.setLabelPosition = function ( labelPosition
) {
10792 this.labelPosition
= labelPosition
;
10793 if ( this.label
) {
10794 // If there is no label and we only change the position, #updatePosition is a no-op,
10795 // but it takes really a lot of work to do nothing.
10796 this.updatePosition();
10802 * Update the position of the inline label.
10804 * This method is called by #setLabelPosition, and can also be called on its own if
10805 * something causes the label to be mispositioned.
10809 OO
.ui
.TextInputWidget
.prototype.updatePosition = function () {
10810 var after
= this.labelPosition
=== 'after';
10813 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label
&& after
)
10814 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label
&& !after
);
10816 this.valCache
= null;
10817 this.scrollWidth
= null;
10818 this.positionLabel();
10824 * Position the label by setting the correct padding on the input.
10829 OO
.ui
.TextInputWidget
.prototype.positionLabel = function () {
10830 var after
, rtl
, property
, newCss
;
10832 if ( this.isWaitingToBeAttached
) {
10833 // #onElementAttach will be called soon, which calls this method
10838 'padding-right': '',
10842 if ( this.label
) {
10843 this.$element
.append( this.$label
);
10845 this.$label
.detach();
10846 // Clear old values if present
10847 this.$input
.css( newCss
);
10851 after
= this.labelPosition
=== 'after';
10852 rtl
= this.$element
.css( 'direction' ) === 'rtl';
10853 property
= after
=== rtl
? 'padding-left' : 'padding-right';
10855 newCss
[ property
] = this.$label
.outerWidth( true ) + ( after
? this.scrollWidth
: 0 );
10856 // We have to clear the padding on the other side, in case the element direction changed
10857 this.$input
.css( newCss
);
10864 * @extends OO.ui.TextInputWidget
10867 * @param {Object} [config] Configuration options
10869 OO
.ui
.SearchInputWidget
= function OoUiSearchInputWidget( config
) {
10870 config
= $.extend( {
10874 // Parent constructor
10875 OO
.ui
.SearchInputWidget
.parent
.call( this, config
);
10878 this.connect( this, {
10883 this.updateSearchIndicator();
10884 this.connect( this, {
10885 disable
: 'onDisable'
10891 OO
.inheritClass( OO
.ui
.SearchInputWidget
, OO
.ui
.TextInputWidget
);
10899 OO
.ui
.SearchInputWidget
.prototype.getSaneType = function () {
10906 OO
.ui
.SearchInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
10907 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
10908 // Clear the text field
10909 this.setValue( '' );
10916 * Update the 'clear' indicator displayed on type: 'search' text
10917 * fields, hiding it when the field is already empty or when it's not
10920 OO
.ui
.SearchInputWidget
.prototype.updateSearchIndicator = function () {
10921 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
10922 this.setIndicator( null );
10924 this.setIndicator( 'clear' );
10929 * Handle change events.
10933 OO
.ui
.SearchInputWidget
.prototype.onChange = function () {
10934 this.updateSearchIndicator();
10938 * Handle disable events.
10940 * @param {boolean} disabled Element is disabled
10943 OO
.ui
.SearchInputWidget
.prototype.onDisable = function () {
10944 this.updateSearchIndicator();
10950 OO
.ui
.SearchInputWidget
.prototype.setReadOnly = function ( state
) {
10951 OO
.ui
.SearchInputWidget
.parent
.prototype.setReadOnly
.call( this, state
);
10952 this.updateSearchIndicator();
10958 * @extends OO.ui.TextInputWidget
10961 * @param {Object} [config] Configuration options
10962 * @cfg {number} [rows] Number of visible lines in textarea. If used with `autosize`,
10963 * specifies minimum number of rows to display.
10964 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
10965 * Use the #maxRows config to specify a maximum number of displayed rows.
10966 * @cfg {number} [maxRows] Maximum number of rows to display when #autosize is set to true.
10967 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
10969 OO
.ui
.MultilineTextInputWidget
= function OoUiMultilineTextInputWidget( config
) {
10970 config
= $.extend( {
10973 // Parent constructor
10974 OO
.ui
.MultilineTextInputWidget
.parent
.call( this, config
);
10977 this.autosize
= !!config
.autosize
;
10978 this.minRows
= config
.rows
!== undefined ? config
.rows
: '';
10979 this.maxRows
= config
.maxRows
|| Math
.max( 2 * ( this.minRows
|| 0 ), 10 );
10981 // Clone for resizing
10982 if ( this.autosize
) {
10983 this.$clone
= this.$input
10985 .removeAttr( 'id' )
10986 .removeAttr( 'name' )
10987 .insertAfter( this.$input
)
10988 .attr( 'aria-hidden', 'true' )
10989 .addClass( 'oo-ui-element-hidden' );
10993 this.connect( this, {
10998 if ( config
.rows
) {
10999 this.$input
.attr( 'rows', config
.rows
);
11001 if ( this.autosize
) {
11002 this.$input
.addClass( 'oo-ui-textInputWidget-autosized' );
11003 this.isWaitingToBeAttached
= true;
11004 this.installParentChangeDetector();
11010 OO
.inheritClass( OO
.ui
.MultilineTextInputWidget
, OO
.ui
.TextInputWidget
);
11012 /* Static Methods */
11017 OO
.ui
.MultilineTextInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
11018 var state
= OO
.ui
.MultilineTextInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
11019 state
.scrollTop
= config
.$input
.scrollTop();
11028 OO
.ui
.MultilineTextInputWidget
.prototype.onElementAttach = function () {
11029 OO
.ui
.MultilineTextInputWidget
.parent
.prototype.onElementAttach
.call( this );
11034 * Handle change events.
11038 OO
.ui
.MultilineTextInputWidget
.prototype.onChange = function () {
11045 OO
.ui
.MultilineTextInputWidget
.prototype.updatePosition = function () {
11046 OO
.ui
.MultilineTextInputWidget
.parent
.prototype.updatePosition
.call( this );
11053 * Modify to emit 'enter' on Ctrl/Meta+Enter, instead of plain Enter
11055 OO
.ui
.MultilineTextInputWidget
.prototype.onKeyPress = function ( e
) {
11057 ( e
.which
=== OO
.ui
.Keys
.ENTER
&& ( e
.ctrlKey
|| e
.metaKey
) ) ||
11058 // Some platforms emit keycode 10 for ctrl+enter in a textarea
11061 this.emit( 'enter', e
);
11066 * Automatically adjust the size of the text input.
11068 * This only affects multiline inputs that are {@link #autosize autosized}.
11073 OO
.ui
.MultilineTextInputWidget
.prototype.adjustSize = function () {
11074 var scrollHeight
, innerHeight
, outerHeight
, maxInnerHeight
, measurementError
,
11075 idealHeight
, newHeight
, scrollWidth
, property
;
11077 if ( this.$input
.val() !== this.valCache
) {
11078 if ( this.autosize
) {
11080 .val( this.$input
.val() )
11081 .attr( 'rows', this.minRows
)
11082 // Set inline height property to 0 to measure scroll height
11083 .css( 'height', 0 );
11085 this.$clone
.removeClass( 'oo-ui-element-hidden' );
11087 this.valCache
= this.$input
.val();
11089 scrollHeight
= this.$clone
[ 0 ].scrollHeight
;
11091 // Remove inline height property to measure natural heights
11092 this.$clone
.css( 'height', '' );
11093 innerHeight
= this.$clone
.innerHeight();
11094 outerHeight
= this.$clone
.outerHeight();
11096 // Measure max rows height
11098 .attr( 'rows', this.maxRows
)
11099 .css( 'height', 'auto' )
11101 maxInnerHeight
= this.$clone
.innerHeight();
11103 // Difference between reported innerHeight and scrollHeight with no scrollbars present.
11104 // This is sometimes non-zero on Blink-based browsers, depending on zoom level.
11105 measurementError
= maxInnerHeight
- this.$clone
[ 0 ].scrollHeight
;
11106 idealHeight
= Math
.min( maxInnerHeight
, scrollHeight
+ measurementError
);
11108 this.$clone
.addClass( 'oo-ui-element-hidden' );
11110 // Only apply inline height when expansion beyond natural height is needed
11111 // Use the difference between the inner and outer height as a buffer
11112 newHeight
= idealHeight
> innerHeight
? idealHeight
+ ( outerHeight
- innerHeight
) : '';
11113 if ( newHeight
!== this.styleHeight
) {
11114 this.$input
.css( 'height', newHeight
);
11115 this.styleHeight
= newHeight
;
11116 this.emit( 'resize' );
11119 scrollWidth
= this.$input
[ 0 ].offsetWidth
- this.$input
[ 0 ].clientWidth
;
11120 if ( scrollWidth
!== this.scrollWidth
) {
11121 property
= this.$element
.css( 'direction' ) === 'rtl' ? 'left' : 'right';
11123 this.$label
.css( { right
: '', left
: '' } );
11124 this.$indicator
.css( { right
: '', left
: '' } );
11126 if ( scrollWidth
) {
11127 this.$indicator
.css( property
, scrollWidth
);
11128 if ( this.labelPosition
=== 'after' ) {
11129 this.$label
.css( property
, scrollWidth
);
11133 this.scrollWidth
= scrollWidth
;
11134 this.positionLabel();
11144 OO
.ui
.MultilineTextInputWidget
.prototype.getInputElement = function () {
11145 return $( '<textarea>' );
11149 * Check if the input automatically adjusts its size.
11151 * @return {boolean}
11153 OO
.ui
.MultilineTextInputWidget
.prototype.isAutosizing = function () {
11154 return !!this.autosize
;
11160 OO
.ui
.MultilineTextInputWidget
.prototype.restorePreInfuseState = function ( state
) {
11161 OO
.ui
.MultilineTextInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
11162 if ( state
.scrollTop
!== undefined ) {
11163 this.$input
.scrollTop( state
.scrollTop
);
11168 * ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
11169 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
11170 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
11172 * - by typing a value in the text input field. If the value exactly matches the value of a menu
11173 * option, that option will appear to be selected.
11174 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
11177 * After the user chooses an option, its `data` will be used as a new value for the widget.
11178 * A `label` also can be specified for each option: if given, it will be shown instead of the
11179 * `data` in the dropdown menu.
11181 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
11183 * For more information about menus and options, please see the [OOUI documentation on MediaWiki][1].
11186 * // Example: A ComboBoxInputWidget.
11187 * var comboBox = new OO.ui.ComboBoxInputWidget( {
11188 * value: 'Option 1',
11190 * { data: 'Option 1' },
11191 * { data: 'Option 2' },
11192 * { data: 'Option 3' }
11195 * $( 'body' ).append( comboBox.$element );
11198 * // Example: A ComboBoxInputWidget with additional option labels.
11199 * var comboBox = new OO.ui.ComboBoxInputWidget( {
11200 * value: 'Option 1',
11203 * data: 'Option 1',
11204 * label: 'Option One'
11207 * data: 'Option 2',
11208 * label: 'Option Two'
11211 * data: 'Option 3',
11212 * label: 'Option Three'
11216 * $( 'body' ).append( comboBox.$element );
11218 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
11221 * @extends OO.ui.TextInputWidget
11224 * @param {Object} [config] Configuration options
11225 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
11226 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
11227 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
11228 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
11229 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
11230 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
11232 OO
.ui
.ComboBoxInputWidget
= function OoUiComboBoxInputWidget( config
) {
11233 // Configuration initialization
11234 config
= $.extend( {
11235 autocomplete
: false
11238 // ComboBoxInputWidget shouldn't support `multiline`
11239 config
.multiline
= false;
11241 // See InputWidget#reusePreInfuseDOM about `config.$input`
11242 if ( config
.$input
) {
11243 config
.$input
.removeAttr( 'list' );
11246 // Parent constructor
11247 OO
.ui
.ComboBoxInputWidget
.parent
.call( this, config
);
11250 this.$overlay
= ( config
.$overlay
=== true ? OO
.ui
.getDefaultOverlay() : config
.$overlay
) || this.$element
;
11251 this.dropdownButton
= new OO
.ui
.ButtonWidget( {
11252 classes
: [ 'oo-ui-comboBoxInputWidget-dropdownButton' ],
11254 disabled
: this.disabled
11256 this.menu
= new OO
.ui
.MenuSelectWidget( $.extend(
11260 $floatableContainer
: this.$element
,
11261 disabled
: this.isDisabled()
11267 this.connect( this, {
11268 change
: 'onInputChange',
11269 enter
: 'onInputEnter'
11271 this.dropdownButton
.connect( this, {
11272 click
: 'onDropdownButtonClick'
11274 this.menu
.connect( this, {
11275 choose
: 'onMenuChoose',
11276 add
: 'onMenuItemsChange',
11277 remove
: 'onMenuItemsChange',
11278 toggle
: 'onMenuToggle'
11282 this.$input
.attr( {
11284 'aria-owns': this.menu
.getElementId(),
11285 'aria-autocomplete': 'list'
11287 // Do not override options set via config.menu.items
11288 if ( config
.options
!== undefined ) {
11289 this.setOptions( config
.options
);
11291 this.$field
= $( '<div>' )
11292 .addClass( 'oo-ui-comboBoxInputWidget-field' )
11293 .append( this.$input
, this.dropdownButton
.$element
);
11295 .addClass( 'oo-ui-comboBoxInputWidget' )
11296 .append( this.$field
);
11297 this.$overlay
.append( this.menu
.$element
);
11298 this.onMenuItemsChange();
11303 OO
.inheritClass( OO
.ui
.ComboBoxInputWidget
, OO
.ui
.TextInputWidget
);
11308 * Get the combobox's menu.
11310 * @return {OO.ui.MenuSelectWidget} Menu widget
11312 OO
.ui
.ComboBoxInputWidget
.prototype.getMenu = function () {
11317 * Get the combobox's text input widget.
11319 * @return {OO.ui.TextInputWidget} Text input widget
11321 OO
.ui
.ComboBoxInputWidget
.prototype.getInput = function () {
11326 * Handle input change events.
11329 * @param {string} value New value
11331 OO
.ui
.ComboBoxInputWidget
.prototype.onInputChange = function ( value
) {
11332 var match
= this.menu
.findItemFromData( value
);
11334 this.menu
.selectItem( match
);
11335 if ( this.menu
.findHighlightedItem() ) {
11336 this.menu
.highlightItem( match
);
11339 if ( !this.isDisabled() ) {
11340 this.menu
.toggle( true );
11345 * Handle input enter events.
11349 OO
.ui
.ComboBoxInputWidget
.prototype.onInputEnter = function () {
11350 if ( !this.isDisabled() ) {
11351 this.menu
.toggle( false );
11356 * Handle button click events.
11360 OO
.ui
.ComboBoxInputWidget
.prototype.onDropdownButtonClick = function () {
11361 this.menu
.toggle();
11366 * Handle menu choose events.
11369 * @param {OO.ui.OptionWidget} item Chosen item
11371 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuChoose = function ( item
) {
11372 this.setValue( item
.getData() );
11376 * Handle menu item change events.
11380 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuItemsChange = function () {
11381 var match
= this.menu
.findItemFromData( this.getValue() );
11382 this.menu
.selectItem( match
);
11383 if ( this.menu
.findHighlightedItem() ) {
11384 this.menu
.highlightItem( match
);
11386 this.$element
.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu
.isEmpty() );
11390 * Handle menu toggle events.
11393 * @param {boolean} isVisible Open state of the menu
11395 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuToggle = function ( isVisible
) {
11396 this.$element
.toggleClass( 'oo-ui-comboBoxInputWidget-open', isVisible
);
11402 OO
.ui
.ComboBoxInputWidget
.prototype.setDisabled = function ( disabled
) {
11404 OO
.ui
.ComboBoxInputWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
11406 if ( this.dropdownButton
) {
11407 this.dropdownButton
.setDisabled( this.isDisabled() );
11410 this.menu
.setDisabled( this.isDisabled() );
11417 * Set the options available for this input.
11419 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
11422 OO
.ui
.ComboBoxInputWidget
.prototype.setOptions = function ( options
) {
11425 .addItems( options
.map( function ( opt
) {
11426 return new OO
.ui
.MenuOptionWidget( {
11428 label
: opt
.label
!== undefined ? opt
.label
: opt
.data
11436 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
11437 * which is a widget that is specified by reference before any optional configuration settings.
11439 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
11441 * - **left**: The label is placed before the field-widget and aligned with the left margin.
11442 * A left-alignment is used for forms with many fields.
11443 * - **right**: The label is placed before the field-widget and aligned to the right margin.
11444 * A right-alignment is used for long but familiar forms which users tab through,
11445 * verifying the current field with a quick glance at the label.
11446 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
11447 * that users fill out from top to bottom.
11448 * - **inline**: The label is placed after the field-widget and aligned to the left.
11449 * An inline-alignment is best used with checkboxes or radio buttons.
11451 * Help text can either be:
11453 * - accessed via a help icon that appears in the upper right corner of the rendered field layout, or
11454 * - shown as a subtle explanation below the label.
11456 * If the help text is brief, or is essential to always expose it, set `helpInline` to `true`. If it
11457 * is long or not essential, leave `helpInline` to its default, `false`.
11459 * Please see the [OOUI documentation on MediaWiki] [1] for examples and more information.
11461 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Fields_and_Fieldsets
11464 * @extends OO.ui.Layout
11465 * @mixins OO.ui.mixin.LabelElement
11466 * @mixins OO.ui.mixin.TitledElement
11469 * @param {OO.ui.Widget} fieldWidget Field widget
11470 * @param {Object} [config] Configuration options
11471 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top'
11473 * @cfg {Array} [errors] Error messages about the widget, which will be
11474 * displayed below the widget.
11475 * The array may contain strings or OO.ui.HtmlSnippet instances.
11476 * @cfg {Array} [notices] Notices about the widget, which will be displayed
11477 * below the widget.
11478 * The array may contain strings or OO.ui.HtmlSnippet instances.
11479 * These are more visible than `help` messages when `helpInline` is set, and so
11480 * might be good for transient messages.
11481 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified
11482 * and `helpInline` is `false`, a "help" icon will appear in the upper-right
11483 * corner of the rendered field; clicking it will display the text in a popup.
11484 * If `helpInline` is `true`, then a subtle description will be shown after the
11486 * @cfg {boolean} [helpInline=false] Whether or not the help should be inline,
11487 * or shown when the "help" icon is clicked.
11488 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if
11490 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
11492 * @throws {Error} An error is thrown if no widget is specified
11494 OO
.ui
.FieldLayout
= function OoUiFieldLayout( fieldWidget
, config
) {
11495 // Allow passing positional parameters inside the config object
11496 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
11497 config
= fieldWidget
;
11498 fieldWidget
= config
.fieldWidget
;
11501 // Make sure we have required constructor arguments
11502 if ( fieldWidget
=== undefined ) {
11503 throw new Error( 'Widget not found' );
11506 // Configuration initialization
11507 config
= $.extend( { align
: 'left', helpInline
: false }, config
);
11509 // Parent constructor
11510 OO
.ui
.FieldLayout
.parent
.call( this, config
);
11512 // Mixin constructors
11513 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, {
11514 $label
: $( '<label>' )
11516 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
11519 this.fieldWidget
= fieldWidget
;
11522 this.$field
= this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
11523 this.$messages
= $( '<ul>' );
11524 this.$header
= $( '<span>' );
11525 this.$body
= $( '<div>' );
11527 this.helpInline
= config
.helpInline
;
11530 this.fieldWidget
.connect( this, { disable
: 'onFieldDisable' } );
11533 this.$help
= config
.help
?
11534 this.createHelpElement( config
.help
, config
.$overlay
) :
11536 if ( this.fieldWidget
.getInputId() ) {
11537 this.$label
.attr( 'for', this.fieldWidget
.getInputId() );
11538 if ( this.helpInline
) {
11539 this.$help
.attr( 'for', this.fieldWidget
.getInputId() );
11542 this.$label
.on( 'click', function () {
11543 this.fieldWidget
.simulateLabelClick();
11545 if ( this.helpInline
) {
11546 this.$help
.on( 'click', function () {
11547 this.fieldWidget
.simulateLabelClick();
11552 .addClass( 'oo-ui-fieldLayout' )
11553 .toggleClass( 'oo-ui-fieldLayout-disabled', this.fieldWidget
.isDisabled() )
11554 .append( this.$body
);
11555 this.$body
.addClass( 'oo-ui-fieldLayout-body' );
11556 this.$header
.addClass( 'oo-ui-fieldLayout-header' );
11557 this.$messages
.addClass( 'oo-ui-fieldLayout-messages' );
11559 .addClass( 'oo-ui-fieldLayout-field' )
11560 .append( this.fieldWidget
.$element
);
11562 this.setErrors( config
.errors
|| [] );
11563 this.setNotices( config
.notices
|| [] );
11564 this.setAlignment( config
.align
);
11565 // Call this again to take into account the widget's accessKey
11566 this.updateTitle();
11571 OO
.inheritClass( OO
.ui
.FieldLayout
, OO
.ui
.Layout
);
11572 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.LabelElement
);
11573 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.TitledElement
);
11578 * Handle field disable events.
11581 * @param {boolean} value Field is disabled
11583 OO
.ui
.FieldLayout
.prototype.onFieldDisable = function ( value
) {
11584 this.$element
.toggleClass( 'oo-ui-fieldLayout-disabled', value
);
11588 * Get the widget contained by the field.
11590 * @return {OO.ui.Widget} Field widget
11592 OO
.ui
.FieldLayout
.prototype.getField = function () {
11593 return this.fieldWidget
;
11597 * Return `true` if the given field widget can be used with `'inline'` alignment (see
11598 * #setAlignment). Return `false` if it can't or if this can't be determined.
11600 * @return {boolean}
11602 OO
.ui
.FieldLayout
.prototype.isFieldInline = function () {
11603 // This is very simplistic, but should be good enough.
11604 return this.getField().$element
.prop( 'tagName' ).toLowerCase() === 'span';
11609 * @param {string} kind 'error' or 'notice'
11610 * @param {string|OO.ui.HtmlSnippet} text
11613 OO
.ui
.FieldLayout
.prototype.makeMessage = function ( kind
, text
) {
11614 var $listItem
, $icon
, message
;
11615 $listItem
= $( '<li>' );
11616 if ( kind
=== 'error' ) {
11617 $icon
= new OO
.ui
.IconWidget( { icon
: 'alert', flags
: [ 'warning' ] } ).$element
;
11618 $listItem
.attr( 'role', 'alert' );
11619 } else if ( kind
=== 'notice' ) {
11620 $icon
= new OO
.ui
.IconWidget( { icon
: 'notice' } ).$element
;
11624 message
= new OO
.ui
.LabelWidget( { label
: text
} );
11626 .append( $icon
, message
.$element
)
11627 .addClass( 'oo-ui-fieldLayout-messages-' + kind
);
11632 * Set the field alignment mode.
11635 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
11638 OO
.ui
.FieldLayout
.prototype.setAlignment = function ( value
) {
11639 if ( value
!== this.align
) {
11640 // Default to 'left'
11641 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value
) === -1 ) {
11645 if ( value
=== 'inline' && !this.isFieldInline() ) {
11648 // Reorder elements
11650 if ( this.helpInline
) {
11651 if ( value
=== 'top' ) {
11652 this.$header
.append( this.$label
);
11653 this.$body
.append( this.$header
, this.$field
, this.$help
);
11654 } else if ( value
=== 'inline' ) {
11655 this.$header
.append( this.$label
, this.$help
);
11656 this.$body
.append( this.$field
, this.$header
);
11658 this.$header
.append( this.$label
, this.$help
);
11659 this.$body
.append( this.$header
, this.$field
);
11662 if ( value
=== 'top' ) {
11663 this.$header
.append( this.$help
, this.$label
);
11664 this.$body
.append( this.$header
, this.$field
);
11665 } else if ( value
=== 'inline' ) {
11666 this.$header
.append( this.$help
, this.$label
);
11667 this.$body
.append( this.$field
, this.$header
);
11669 this.$header
.append( this.$label
);
11670 this.$body
.append( this.$header
, this.$help
, this.$field
);
11673 // Set classes. The following classes can be used here:
11674 // * oo-ui-fieldLayout-align-left
11675 // * oo-ui-fieldLayout-align-right
11676 // * oo-ui-fieldLayout-align-top
11677 // * oo-ui-fieldLayout-align-inline
11678 if ( this.align
) {
11679 this.$element
.removeClass( 'oo-ui-fieldLayout-align-' + this.align
);
11681 this.$element
.addClass( 'oo-ui-fieldLayout-align-' + value
);
11682 this.align
= value
;
11689 * Set the list of error messages.
11691 * @param {Array} errors Error messages about the widget, which will be displayed below the widget.
11692 * The array may contain strings or OO.ui.HtmlSnippet instances.
11695 OO
.ui
.FieldLayout
.prototype.setErrors = function ( errors
) {
11696 this.errors
= errors
.slice();
11697 this.updateMessages();
11702 * Set the list of notice messages.
11704 * @param {Array} notices Notices about the widget, which will be displayed below the widget.
11705 * The array may contain strings or OO.ui.HtmlSnippet instances.
11708 OO
.ui
.FieldLayout
.prototype.setNotices = function ( notices
) {
11709 this.notices
= notices
.slice();
11710 this.updateMessages();
11715 * Update the rendering of error and notice messages.
11719 OO
.ui
.FieldLayout
.prototype.updateMessages = function () {
11721 this.$messages
.empty();
11723 if ( this.errors
.length
|| this.notices
.length
) {
11724 this.$body
.after( this.$messages
);
11726 this.$messages
.remove();
11730 for ( i
= 0; i
< this.notices
.length
; i
++ ) {
11731 this.$messages
.append( this.makeMessage( 'notice', this.notices
[ i
] ) );
11733 for ( i
= 0; i
< this.errors
.length
; i
++ ) {
11734 this.$messages
.append( this.makeMessage( 'error', this.errors
[ i
] ) );
11739 * Include information about the widget's accessKey in our title. TitledElement calls this method.
11740 * (This is a bit of a hack.)
11743 * @param {string} title Tooltip label for 'title' attribute
11746 OO
.ui
.FieldLayout
.prototype.formatTitleWithAccessKey = function ( title
) {
11747 if ( this.fieldWidget
&& this.fieldWidget
.formatTitleWithAccessKey
) {
11748 return this.fieldWidget
.formatTitleWithAccessKey( title
);
11754 * Creates and returns the help element. Also sets the `aria-describedby`
11755 * attribute on the main element of the `fieldWidget`.
11758 * @param {string|OO.ui.HtmlSnippet} [help] Help text.
11759 * @param {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup.
11760 * @return {jQuery} The element that should become `this.$help`.
11762 OO
.ui
.FieldLayout
.prototype.createHelpElement = function ( help
, $overlay
) {
11763 var helpId
, helpWidget
;
11765 if ( this.helpInline
) {
11766 helpWidget
= new OO
.ui
.LabelWidget( {
11768 classes
: [ 'oo-ui-inline-help' ]
11771 helpId
= helpWidget
.getElementId();
11773 helpWidget
= new OO
.ui
.PopupButtonWidget( {
11774 $overlay
: $overlay
,
11778 classes
: [ 'oo-ui-fieldLayout-help' ],
11781 label
: OO
.ui
.msg( 'ooui-field-help' ),
11782 invisibleLabel
: true
11784 if ( help
instanceof OO
.ui
.HtmlSnippet
) {
11785 helpWidget
.getPopup().$body
.html( help
.toString() );
11787 helpWidget
.getPopup().$body
.text( help
);
11790 helpId
= helpWidget
.getPopup().getBodyId();
11793 // Set the 'aria-describedby' attribute on the fieldWidget
11794 // Preference given to an input or a button
11796 this.fieldWidget
.$input
||
11797 this.fieldWidget
.$button
||
11798 this.fieldWidget
.$element
11799 ).attr( 'aria-describedby', helpId
);
11801 return helpWidget
.$element
;
11805 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
11806 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
11807 * is required and is specified before any optional configuration settings.
11809 * Labels can be aligned in one of four ways:
11811 * - **left**: The label is placed before the field-widget and aligned with the left margin.
11812 * A left-alignment is used for forms with many fields.
11813 * - **right**: The label is placed before the field-widget and aligned to the right margin.
11814 * A right-alignment is used for long but familiar forms which users tab through,
11815 * verifying the current field with a quick glance at the label.
11816 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
11817 * that users fill out from top to bottom.
11818 * - **inline**: The label is placed after the field-widget and aligned to the left.
11819 * An inline-alignment is best used with checkboxes or radio buttons.
11821 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
11822 * text is specified.
11825 * // Example of an ActionFieldLayout
11826 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
11827 * new OO.ui.TextInputWidget( {
11828 * placeholder: 'Field widget'
11830 * new OO.ui.ButtonWidget( {
11834 * label: 'An ActionFieldLayout. This label is aligned top',
11836 * help: 'This is help text'
11840 * $( 'body' ).append( actionFieldLayout.$element );
11843 * @extends OO.ui.FieldLayout
11846 * @param {OO.ui.Widget} fieldWidget Field widget
11847 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
11848 * @param {Object} config
11850 OO
.ui
.ActionFieldLayout
= function OoUiActionFieldLayout( fieldWidget
, buttonWidget
, config
) {
11851 // Allow passing positional parameters inside the config object
11852 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
11853 config
= fieldWidget
;
11854 fieldWidget
= config
.fieldWidget
;
11855 buttonWidget
= config
.buttonWidget
;
11858 // Parent constructor
11859 OO
.ui
.ActionFieldLayout
.parent
.call( this, fieldWidget
, config
);
11862 this.buttonWidget
= buttonWidget
;
11863 this.$button
= $( '<span>' );
11864 this.$input
= this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
11868 .addClass( 'oo-ui-actionFieldLayout' );
11870 .addClass( 'oo-ui-actionFieldLayout-button' )
11871 .append( this.buttonWidget
.$element
);
11873 .addClass( 'oo-ui-actionFieldLayout-input' )
11874 .append( this.fieldWidget
.$element
);
11876 .append( this.$input
, this.$button
);
11881 OO
.inheritClass( OO
.ui
.ActionFieldLayout
, OO
.ui
.FieldLayout
);
11884 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
11885 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
11886 * configured with a label as well. For more information and examples,
11887 * please see the [OOUI documentation on MediaWiki][1].
11890 * // Example of a fieldset layout
11891 * var input1 = new OO.ui.TextInputWidget( {
11892 * placeholder: 'A text input field'
11895 * var input2 = new OO.ui.TextInputWidget( {
11896 * placeholder: 'A text input field'
11899 * var fieldset = new OO.ui.FieldsetLayout( {
11900 * label: 'Example of a fieldset layout'
11903 * fieldset.addItems( [
11904 * new OO.ui.FieldLayout( input1, {
11905 * label: 'Field One'
11907 * new OO.ui.FieldLayout( input2, {
11908 * label: 'Field Two'
11911 * $( 'body' ).append( fieldset.$element );
11913 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Fields_and_Fieldsets
11916 * @extends OO.ui.Layout
11917 * @mixins OO.ui.mixin.IconElement
11918 * @mixins OO.ui.mixin.LabelElement
11919 * @mixins OO.ui.mixin.GroupElement
11922 * @param {Object} [config] Configuration options
11923 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
11924 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
11925 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
11926 * For important messages, you are advised to use `notices`, as they are always shown.
11927 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if `help` is given.
11928 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
11930 OO
.ui
.FieldsetLayout
= function OoUiFieldsetLayout( config
) {
11931 // Configuration initialization
11932 config
= config
|| {};
11934 // Parent constructor
11935 OO
.ui
.FieldsetLayout
.parent
.call( this, config
);
11937 // Mixin constructors
11938 OO
.ui
.mixin
.IconElement
.call( this, config
);
11939 OO
.ui
.mixin
.LabelElement
.call( this, config
);
11940 OO
.ui
.mixin
.GroupElement
.call( this, config
);
11943 this.$header
= $( '<legend>' );
11944 if ( config
.help
) {
11945 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
11946 $overlay
: config
.$overlay
,
11950 classes
: [ 'oo-ui-fieldsetLayout-help' ],
11953 label
: OO
.ui
.msg( 'ooui-field-help' ),
11954 invisibleLabel
: true
11956 if ( config
.help
instanceof OO
.ui
.HtmlSnippet
) {
11957 this.popupButtonWidget
.getPopup().$body
.html( config
.help
.toString() );
11959 this.popupButtonWidget
.getPopup().$body
.text( config
.help
);
11961 this.$help
= this.popupButtonWidget
.$element
;
11963 this.$help
= $( [] );
11968 .addClass( 'oo-ui-fieldsetLayout-header' )
11969 .append( this.$icon
, this.$label
, this.$help
);
11970 this.$group
.addClass( 'oo-ui-fieldsetLayout-group' );
11972 .addClass( 'oo-ui-fieldsetLayout' )
11973 .prepend( this.$header
, this.$group
);
11974 if ( Array
.isArray( config
.items
) ) {
11975 this.addItems( config
.items
);
11981 OO
.inheritClass( OO
.ui
.FieldsetLayout
, OO
.ui
.Layout
);
11982 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.IconElement
);
11983 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.LabelElement
);
11984 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.GroupElement
);
11986 /* Static Properties */
11992 OO
.ui
.FieldsetLayout
.static.tagName
= 'fieldset';
11995 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
11996 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
11997 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
11998 * See the [OOUI documentation on MediaWiki] [1] for more information and examples.
12000 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
12001 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
12002 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
12003 * some fancier controls. Some controls have both regular and InputWidget variants, for example
12004 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
12005 * often have simplified APIs to match the capabilities of HTML forms.
12006 * See the [OOUI documentation on MediaWiki] [2] for more information about InputWidgets.
12008 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Forms
12009 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
12012 * // Example of a form layout that wraps a fieldset layout
12013 * var input1 = new OO.ui.TextInputWidget( {
12014 * placeholder: 'Username'
12016 * var input2 = new OO.ui.TextInputWidget( {
12017 * placeholder: 'Password',
12020 * var submit = new OO.ui.ButtonInputWidget( {
12024 * var fieldset = new OO.ui.FieldsetLayout( {
12025 * label: 'A form layout'
12027 * fieldset.addItems( [
12028 * new OO.ui.FieldLayout( input1, {
12029 * label: 'Username',
12032 * new OO.ui.FieldLayout( input2, {
12033 * label: 'Password',
12036 * new OO.ui.FieldLayout( submit )
12038 * var form = new OO.ui.FormLayout( {
12039 * items: [ fieldset ],
12040 * action: '/api/formhandler',
12043 * $( 'body' ).append( form.$element );
12046 * @extends OO.ui.Layout
12047 * @mixins OO.ui.mixin.GroupElement
12050 * @param {Object} [config] Configuration options
12051 * @cfg {string} [method] HTML form `method` attribute
12052 * @cfg {string} [action] HTML form `action` attribute
12053 * @cfg {string} [enctype] HTML form `enctype` attribute
12054 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
12056 OO
.ui
.FormLayout
= function OoUiFormLayout( config
) {
12059 // Configuration initialization
12060 config
= config
|| {};
12062 // Parent constructor
12063 OO
.ui
.FormLayout
.parent
.call( this, config
);
12065 // Mixin constructors
12066 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
12069 this.$element
.on( 'submit', this.onFormSubmit
.bind( this ) );
12071 // Make sure the action is safe
12072 action
= config
.action
;
12073 if ( action
!== undefined && !OO
.ui
.isSafeUrl( action
) ) {
12074 action
= './' + action
;
12079 .addClass( 'oo-ui-formLayout' )
12081 method
: config
.method
,
12083 enctype
: config
.enctype
12085 if ( Array
.isArray( config
.items
) ) {
12086 this.addItems( config
.items
);
12092 OO
.inheritClass( OO
.ui
.FormLayout
, OO
.ui
.Layout
);
12093 OO
.mixinClass( OO
.ui
.FormLayout
, OO
.ui
.mixin
.GroupElement
);
12098 * A 'submit' event is emitted when the form is submitted.
12103 /* Static Properties */
12109 OO
.ui
.FormLayout
.static.tagName
= 'form';
12114 * Handle form submit events.
12117 * @param {jQuery.Event} e Submit event
12120 OO
.ui
.FormLayout
.prototype.onFormSubmit = function () {
12121 if ( this.emit( 'submit' ) ) {
12127 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
12128 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
12131 * // Example of a panel layout
12132 * var panel = new OO.ui.PanelLayout( {
12136 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
12138 * $( 'body' ).append( panel.$element );
12141 * @extends OO.ui.Layout
12144 * @param {Object} [config] Configuration options
12145 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
12146 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
12147 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
12148 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
12150 OO
.ui
.PanelLayout
= function OoUiPanelLayout( config
) {
12151 // Configuration initialization
12152 config
= $.extend( {
12159 // Parent constructor
12160 OO
.ui
.PanelLayout
.parent
.call( this, config
);
12163 this.$element
.addClass( 'oo-ui-panelLayout' );
12164 if ( config
.scrollable
) {
12165 this.$element
.addClass( 'oo-ui-panelLayout-scrollable' );
12167 if ( config
.padded
) {
12168 this.$element
.addClass( 'oo-ui-panelLayout-padded' );
12170 if ( config
.expanded
) {
12171 this.$element
.addClass( 'oo-ui-panelLayout-expanded' );
12173 if ( config
.framed
) {
12174 this.$element
.addClass( 'oo-ui-panelLayout-framed' );
12180 OO
.inheritClass( OO
.ui
.PanelLayout
, OO
.ui
.Layout
);
12185 * Focus the panel layout
12187 * The default implementation just focuses the first focusable element in the panel
12189 OO
.ui
.PanelLayout
.prototype.focus = function () {
12190 OO
.ui
.findFocusable( this.$element
).focus();
12194 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
12195 * items), with small margins between them. Convenient when you need to put a number of block-level
12196 * widgets on a single line next to each other.
12198 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
12201 * // HorizontalLayout with a text input and a label
12202 * var layout = new OO.ui.HorizontalLayout( {
12204 * new OO.ui.LabelWidget( { label: 'Label' } ),
12205 * new OO.ui.TextInputWidget( { value: 'Text' } )
12208 * $( 'body' ).append( layout.$element );
12211 * @extends OO.ui.Layout
12212 * @mixins OO.ui.mixin.GroupElement
12215 * @param {Object} [config] Configuration options
12216 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
12218 OO
.ui
.HorizontalLayout
= function OoUiHorizontalLayout( config
) {
12219 // Configuration initialization
12220 config
= config
|| {};
12222 // Parent constructor
12223 OO
.ui
.HorizontalLayout
.parent
.call( this, config
);
12225 // Mixin constructors
12226 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
12229 this.$element
.addClass( 'oo-ui-horizontalLayout' );
12230 if ( Array
.isArray( config
.items
) ) {
12231 this.addItems( config
.items
);
12237 OO
.inheritClass( OO
.ui
.HorizontalLayout
, OO
.ui
.Layout
);
12238 OO
.mixinClass( OO
.ui
.HorizontalLayout
, OO
.ui
.mixin
.GroupElement
);
12241 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
12242 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
12243 * (to adjust the value in increments) to allow the user to enter a number.
12246 * // Example: A NumberInputWidget.
12247 * var numberInput = new OO.ui.NumberInputWidget( {
12248 * label: 'NumberInputWidget',
12249 * input: { value: 5 },
12253 * $( 'body' ).append( numberInput.$element );
12256 * @extends OO.ui.TextInputWidget
12259 * @param {Object} [config] Configuration options
12260 * @cfg {Object} [minusButton] Configuration options to pass to the
12261 * {@link OO.ui.ButtonWidget decrementing button widget}.
12262 * @cfg {Object} [plusButton] Configuration options to pass to the
12263 * {@link OO.ui.ButtonWidget incrementing button widget}.
12264 * @cfg {number} [min=-Infinity] Minimum allowed value
12265 * @cfg {number} [max=Infinity] Maximum allowed value
12266 * @cfg {number|null} [step] If specified, the field only accepts values that are multiples of this.
12267 * @cfg {number} [buttonStep=step||1] Delta when using the buttons or up/down arrow keys.
12268 * Defaults to `step` if specified, otherwise `1`.
12269 * @cfg {number} [pageStep=10*buttonStep] Delta when using the page-up/page-down keys.
12270 * Defaults to 10 times `buttonStep`.
12271 * @cfg {boolean} [showButtons=true] Whether to show the plus and minus buttons.
12273 OO
.ui
.NumberInputWidget
= function OoUiNumberInputWidget( config
) {
12274 var $field
= $( '<div>' )
12275 .addClass( 'oo-ui-numberInputWidget-field' );
12277 // Configuration initialization
12278 config
= $.extend( {
12284 // For backward compatibility
12285 $.extend( config
, config
.input
);
12288 // Parent constructor
12289 OO
.ui
.NumberInputWidget
.parent
.call( this, $.extend( config
, {
12293 if ( config
.showButtons
) {
12294 this.minusButton
= new OO
.ui
.ButtonWidget( $.extend(
12296 disabled
: this.isDisabled(),
12298 classes
: [ 'oo-ui-numberInputWidget-minusButton' ],
12303 this.minusButton
.$element
.attr( 'aria-hidden', 'true' );
12304 this.plusButton
= new OO
.ui
.ButtonWidget( $.extend(
12306 disabled
: this.isDisabled(),
12308 classes
: [ 'oo-ui-numberInputWidget-plusButton' ],
12313 this.plusButton
.$element
.attr( 'aria-hidden', 'true' );
12318 keydown
: this.onKeyDown
.bind( this ),
12319 'wheel mousewheel DOMMouseScroll': this.onWheel
.bind( this )
12321 if ( config
.showButtons
) {
12322 this.plusButton
.connect( this, {
12323 click
: [ 'onButtonClick', +1 ]
12325 this.minusButton
.connect( this, {
12326 click
: [ 'onButtonClick', -1 ]
12331 $field
.append( this.$input
);
12332 if ( config
.showButtons
) {
12334 .prepend( this.minusButton
.$element
)
12335 .append( this.plusButton
.$element
);
12339 if ( config
.allowInteger
|| config
.isInteger
) {
12340 // Backward compatibility
12343 this.setRange( config
.min
, config
.max
);
12344 this.setStep( config
.buttonStep
, config
.pageStep
, config
.step
);
12345 // Set the validation method after we set step and range
12346 // so that it doesn't immediately call setValidityFlag
12347 this.setValidation( this.validateNumber
.bind( this ) );
12350 .addClass( 'oo-ui-numberInputWidget' )
12351 .toggleClass( 'oo-ui-numberInputWidget-buttoned', config
.showButtons
)
12357 OO
.inheritClass( OO
.ui
.NumberInputWidget
, OO
.ui
.TextInputWidget
);
12361 // Backward compatibility
12362 OO
.ui
.NumberInputWidget
.prototype.setAllowInteger = function ( flag
) {
12363 this.setStep( flag
? 1 : null );
12365 // Backward compatibility
12366 OO
.ui
.NumberInputWidget
.prototype.setIsInteger
= OO
.ui
.NumberInputWidget
.prototype.setAllowInteger
;
12368 // Backward compatibility
12369 OO
.ui
.NumberInputWidget
.prototype.getAllowInteger = function () {
12370 return this.step
=== 1;
12372 // Backward compatibility
12373 OO
.ui
.NumberInputWidget
.prototype.getIsInteger
= OO
.ui
.NumberInputWidget
.prototype.getAllowInteger
;
12376 * Set the range of allowed values
12378 * @param {number} min Minimum allowed value
12379 * @param {number} max Maximum allowed value
12381 OO
.ui
.NumberInputWidget
.prototype.setRange = function ( min
, max
) {
12383 throw new Error( 'Minimum (' + min
+ ') must not be greater than maximum (' + max
+ ')' );
12387 this.$input
.attr( 'min', this.min
);
12388 this.$input
.attr( 'max', this.max
);
12389 this.setValidityFlag();
12393 * Get the current range
12395 * @return {number[]} Minimum and maximum values
12397 OO
.ui
.NumberInputWidget
.prototype.getRange = function () {
12398 return [ this.min
, this.max
];
12402 * Set the stepping deltas
12404 * @param {number} [buttonStep=step||1] Delta when using the buttons or up/down arrow keys.
12405 * Defaults to `step` if specified, otherwise `1`.
12406 * @param {number} [pageStep=10*buttonStep] Delta when using the page-up/page-down keys.
12407 * Defaults to 10 times `buttonStep`.
12408 * @param {number|null} [step] If specified, the field only accepts values that are multiples of this.
12410 OO
.ui
.NumberInputWidget
.prototype.setStep = function ( buttonStep
, pageStep
, step
) {
12411 if ( buttonStep
=== undefined ) {
12412 buttonStep
= step
|| 1;
12414 if ( pageStep
=== undefined ) {
12415 pageStep
= 10 * buttonStep
;
12417 if ( step
!== null && step
<= 0 ) {
12418 throw new Error( 'Step value, if given, must be positive' );
12420 if ( buttonStep
<= 0 ) {
12421 throw new Error( 'Button step value must be positive' );
12423 if ( pageStep
<= 0 ) {
12424 throw new Error( 'Page step value must be positive' );
12427 this.buttonStep
= buttonStep
;
12428 this.pageStep
= pageStep
;
12429 this.$input
.attr( 'step', this.step
|| 'any' );
12430 this.setValidityFlag();
12436 OO
.ui
.NumberInputWidget
.prototype.setValue = function ( value
) {
12437 if ( value
=== '' ) {
12438 // Some browsers allow a value in the input even if there isn't one reported by $input.val()
12439 // so here we make sure an 'empty' value is actually displayed as such.
12440 this.$input
.val( '' );
12442 return OO
.ui
.NumberInputWidget
.parent
.prototype.setValue
.call( this, value
);
12446 * Get the current stepping values
12448 * @return {number[]} Button step, page step, and validity step
12450 OO
.ui
.NumberInputWidget
.prototype.getStep = function () {
12451 return [ this.buttonStep
, this.pageStep
, this.step
];
12455 * Get the current value of the widget as a number
12457 * @return {number} May be NaN, or an invalid number
12459 OO
.ui
.NumberInputWidget
.prototype.getNumericValue = function () {
12460 return +this.getValue();
12464 * Adjust the value of the widget
12466 * @param {number} delta Adjustment amount
12468 OO
.ui
.NumberInputWidget
.prototype.adjustValue = function ( delta
) {
12469 var n
, v
= this.getNumericValue();
12472 if ( isNaN( delta
) || !isFinite( delta
) ) {
12473 throw new Error( 'Delta must be a finite number' );
12476 if ( isNaN( v
) ) {
12480 n
= Math
.max( Math
.min( n
, this.max
), this.min
);
12482 n
= Math
.round( n
/ this.step
) * this.step
;
12487 this.setValue( n
);
12494 * @param {string} value Field value
12495 * @return {boolean}
12497 OO
.ui
.NumberInputWidget
.prototype.validateNumber = function ( value
) {
12499 if ( value
=== '' ) {
12500 return !this.isRequired();
12503 if ( isNaN( n
) || !isFinite( n
) ) {
12507 if ( this.step
&& Math
.floor( n
/ this.step
) !== n
/ this.step
) {
12511 if ( n
< this.min
|| n
> this.max
) {
12519 * Handle mouse click events.
12522 * @param {number} dir +1 or -1
12524 OO
.ui
.NumberInputWidget
.prototype.onButtonClick = function ( dir
) {
12525 this.adjustValue( dir
* this.buttonStep
);
12529 * Handle mouse wheel events.
12532 * @param {jQuery.Event} event
12534 OO
.ui
.NumberInputWidget
.prototype.onWheel = function ( event
) {
12537 if ( !this.isDisabled() && this.$input
.is( ':focus' ) ) {
12538 // Standard 'wheel' event
12539 if ( event
.originalEvent
.deltaMode
!== undefined ) {
12540 this.sawWheelEvent
= true;
12542 if ( event
.originalEvent
.deltaY
) {
12543 delta
= -event
.originalEvent
.deltaY
;
12544 } else if ( event
.originalEvent
.deltaX
) {
12545 delta
= event
.originalEvent
.deltaX
;
12548 // Non-standard events
12549 if ( !this.sawWheelEvent
) {
12550 if ( event
.originalEvent
.wheelDeltaX
) {
12551 delta
= -event
.originalEvent
.wheelDeltaX
;
12552 } else if ( event
.originalEvent
.wheelDeltaY
) {
12553 delta
= event
.originalEvent
.wheelDeltaY
;
12554 } else if ( event
.originalEvent
.wheelDelta
) {
12555 delta
= event
.originalEvent
.wheelDelta
;
12556 } else if ( event
.originalEvent
.detail
) {
12557 delta
= -event
.originalEvent
.detail
;
12562 delta
= delta
< 0 ? -1 : 1;
12563 this.adjustValue( delta
* this.buttonStep
);
12571 * Handle key down events.
12574 * @param {jQuery.Event} e Key down event
12576 OO
.ui
.NumberInputWidget
.prototype.onKeyDown = function ( e
) {
12577 if ( !this.isDisabled() ) {
12578 switch ( e
.which
) {
12579 case OO
.ui
.Keys
.UP
:
12580 this.adjustValue( this.buttonStep
);
12582 case OO
.ui
.Keys
.DOWN
:
12583 this.adjustValue( -this.buttonStep
);
12585 case OO
.ui
.Keys
.PAGEUP
:
12586 this.adjustValue( this.pageStep
);
12588 case OO
.ui
.Keys
.PAGEDOWN
:
12589 this.adjustValue( -this.pageStep
);
12598 OO
.ui
.NumberInputWidget
.prototype.setDisabled = function ( disabled
) {
12600 OO
.ui
.NumberInputWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
12602 if ( this.minusButton
) {
12603 this.minusButton
.setDisabled( this.isDisabled() );
12605 if ( this.plusButton
) {
12606 this.plusButton
.setDisabled( this.isDisabled() );
12614 //# sourceMappingURL=oojs-ui-core.js.map.json